简体   繁体   中英

Date Format Conversion in Java

我在项目中要求 将24小时格式转换为12小时格式 ,例如如果它是17:12:01它应该转换为05:12:01

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM