Java String Examples

Java Date to String Example

Want to learn quickly?
Try one of the many quizzes. More than Java 400 questions with detailed answers.

Add Comment

  • import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    public class ConvertDateToStringExample {

    public static void main(String args[]){

    //create new java.util.Date object
    Date date = new Date();

    /*
    * To convert java.util.Date to String, use SimpleDateFormat class.
    */

    /*
    * crate new SimpleDateFormat instance with desired date format.
    * We are going to use yyyy-mm-dd hh:mm:ss here.
    */
    DateFormat dateFormat = new SimpleDateFormat(“yyyy-mm-dd hh:mm:ss”);

    //to convert Date to String, use format method of SimpleDateFormat class.
    String strDate = dateFormat.format(date);

    System.out.println(“Date converted to String: ” + strDate);

    }
    }

    /*
    Output of above given java.util.Date to String example would be
    Date converted to String: 2011-17-10 11:17:50
    */

  • you hav provided us a brilliant code but there is one mistake in that….u should define the format yyyy-MM-dd rather than yyyy-mm-dd.

Sponsors

Facebook Fans

Online Shopping – Flipkart