Reputation: 41
I have a requirement in project to Convert 24 hours format to 12 hours format for example if it is 17:12:01 it should be converted to 05:12:01
Upvotes: 0
Views: 1377
Reputation: 57192
You can use a SimpleDateFormat
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html to format it.
Date date = new Date(yourdate);
// format however you see fit
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
String formatted = format.format(date);
As suggested by Software Monkey, also use a SimpleDateFormat to parse your 24hr date if you don't already have it in millis.
Upvotes: 1
Reputation: 64026
Use two SimpleDateFormat
objects - one to parse and the other to format the time.
Note also that 05:12:01
is not technically a 12 hour time (rather it appears to be an AM 24 hour time, given the lead 0 on the hour and the lack of a meridian designation). You probably want 5:12:01 PM
.
It is possible that a 12 hour SimpleDateFormat will correctly parse a 24 hour time, provided that it is configured for lenient parsing. Just saying, so perhaps you need only one SimpleDateFormat.
Upvotes: 1