kanishk kanishk - 4 months ago 11
Java Question

Java : SimpleDateFormat - Unable to parse a string to a date of desired format

I am trying to parse one string to a format

yyyy-MM-dd
and one to
yyyy-MM-dd HH:mm:ss
.
I am using
SimpleDateFormat
.

I have used the same method successfully earlier, but now something is going wrong. I get the date in the standard format i.e.
Tue Mar 05 00:00:00 GMT+05:30 2012
(for
yyyy-MM-dd
) and
Mon Mar 05 13:01:35 GMT+05:30 2012
(for
yyyy-MM-dd HH:mm:ss
) where as I need them to be
2012-03-05
and
2012-03-05 13:01:35
repectively.

This is what I do :

Date today = new Date();
SimpleDateFormat tsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
today = tsdf.parse(tsdf.format(new Date()));
} catch(Exception e) {
System.out.println("Error occurred"+ e.getMessage());
}

System.out.println(today);


AND

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
// I recieve a string in this format here (refers to 5 march 2012).
myDate = sdf.parse('2012-03-05');
System.out.println(myDate);
} catch(Exception e) {
System.out.println("Error occurred "+ e.getMessage());
}

Answer
today = tsdf.parse(tsdf.format(new Date()));
System.out.println(today);

Looks to me like you expect, that the Date instance gets formatted. That is not the case. A Date instance represents a date that can be formatted "to" a string. It is a class that simply holds a long value (meaning something like "time in milliseconds").

This would give the expected result:

Date today = new Date();
String formattedDate = tsdf.format(today);
System.println(formattedDate);     // <- we print the string!!
Comments