MadN
MadN

Reputation: 1

How to convert into Timestamp format in Java?

I am getting the date time in "1/23/2013 6:57:17 AM" format and need to convert it into "2012-01-01T12:00:00" format. I could have solved the issue by using string functions and separating the date and time and dealing with them individually. But the problem is compunded by the fact that the date format is M/D/YYYY and even time has only h:mm:ss which means i cannot assume the number of characters before each delimiter. I hope someone has dealt with something like this before. Thanks.

Upvotes: 0

Views: 6153

Answers (1)

duffymo
duffymo

Reputation: 309008

No, String functions are not the way to go.

I'd recommend using two DateFormat instances: one for the source format and another for the target format.

DateFormat source = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
source.setLenient(false);
DateFormat target = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
target.setLenient(false);
String dateAsString = "1/23/2013 12:00:00 AM";
Date d = source.parse(dateAsString);
System.out.println(target.format(d));

Upvotes: 3

Related Questions