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());
}
Looks to me like you expect, that the
Dateinstance gets formatted. That is not the case. ADateinstance represents a date that can be formatted “to” a string. It is a class that simply holds alongvalue (meaning something like “time in milliseconds”).This would give the expected result: