Date to String Java

Date to String Java

It is required in Java, many a times in programming, to convert Date to String and also String to Date. To do either, the best class we can use is java.text.SimpleDateFormat. Following explanation gives the first one – Date to String.

Steps

1. Ceate a Date object.
2. Create a SimpleDateFormat object by passing the date format you would like to its constructor.
3. Use foramt() method of SimpleDateFormat and pass the Date object as parameter to format(). format() method returns a String with the same date format style you passed as parameter to SimpleDateFormat constructor.

Following program on Date to String follows the above 3 steps with different date formats and converting each date format into a string representation.

Date to String

The above code is a practical example taking date from the user. The date can be converted also into java.sql.Date to enter into database using JDBC.

SimpleDateFormat sdf1 = new SimpleDateFormat(“yyyy-MM-dd”);
String stringToday1 = sdf1.format(today1);

First choose the format you like and pass it to the SimpleDateFormat constructor. Pass the Date object to format() method. The format() method returns the date object as string in the form of the format passed to SimpleDateFormat constructor.

Precautions

1. Lowercase "m" represents minutes and uppercase "M" represents Month (many people do mistake here only).
2. Lowercase "d" represents date in a month and uppercase "D" represents Day of a week.
3. You cannot compare ddMMyyyy with yyyyMMdd. Both are not equal.
4. Use yyyy\\MM\\dd for yyyy\MM\dd as \ (backslash) is an escape sequence.
5. SimpleDateFormat is not thread-safe; its methods are not synchronized. Better create a separate SimpleDateFormat object for each representation as in the above code when parsing date is done.

It is also important for a developer to familiarize with the utility classes used frequently in coding – Date, Calendar, TimeZone and Locale and GregorianCalendar.

In the following code, the date information is taken from keyboard from the user and converted into Date and then again back to string. It is more a practical example.

Date to String

Would you like to other way of converting String to Date also?

Leave a Reply

Your email address will not be published. Required fields are marked *