简体   繁体   English

Java中的日期格式转换

[英]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. 使用两个SimpleDateFormat对象 - 一个用于解析,另一个用于格式化时间。

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). 另请注意, 05:12:01 :12: 05:12:01在技​​术上不是一个12小时的时间(相反,它似乎是一个AM 24小时的时间,考虑到当时的领先0和没有经络指定)。 You probably want 5:12:01 PM . 你可能想要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. 可能的是,在12小时的SimpleDateFormat将正确地分析24小时的时间,条件是它被配置为宽松的解析。 Just saying, so perhaps you need only one SimpleDateFormat. 只是说,所以也许你只需要一个SimpleDateFormat。

You can use a SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html to format it. 您可以使用SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html对其进行格式化。

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. 正如Software Monkey所建议的那样,如果你还没有以毫秒为单位,也可以使用SimpleDateFormat来解析你的24小时日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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