如何日期和时间换算成12小时格式 [英] how to convert date and time to 12 hour format
问题描述
您好,我有24小时制的日期和时间字符串,但我希望它在12个小时了,怎么我能做到这一点我的字符串是
hello i have a date and time string in 24 hour format but i want it in 12 hour how i can do this my string is
String date_st="12 Nov, 2014 23:13"
我这样做
SimpleDateFormat dateformat = new SimpleDateFormat("dd' 'MMM,' 'yyyy HH:mm aa");
但其未进行转换,根据我的需要它显示23:13 PM
but its not converting according to my need it shows 23:13 PM
我要在下面的格式显示
String con_date= "12 Nov, 2014 11:13 PM"
我怎么能做到这一点?
how i can do this?
推荐答案
您需要两种格式:一个分析,一到格式。你需要从字符串
到日期
一个日期格式
解析,然后格式化日期
到字符串
与其他格式。
You need two formats: one to parse, and one to format. You need to parse from String
to Date
with one DateFormat
, then format that Date
into a String
with the other format.
目前,您的单一的SimpleDateFormat
是一半的 - 你有 HH
这是24小时的,但你也有 AA
这是AM / PM。你想 HH
没有 AA
输入和 HH
的与的的 AA
输出。 (这几乎的从不的适当兼得 HH
和 AA
)
Currently, your single SimpleDateFormat
is half way between - you've got HH
which is 24-hour, but you've also got aa
which is for am/pm. You want HH
without the aa
for input, and hh
with the aa
for output. (It's almost never appropriate to have both HH
and aa
.)
TimeZone utc = TimeZone.getTimeZone("etc/UTC");
DateFormat inputFormat = new SimpleDateFormat("dd MMM, yyyy HH:mm",
Locale.US);
inputFormat.setTimeZone(utc);
DateFormat outputFormat = new SimpleDateFormat("dd MMM, yyyy hh:mm aa",
Locale.US);
outputFormat.setTimeZone(utc);
Date date = inputFormat.parse(input);
String output = outputFormat.format(date);
请注意,我的区域设置为美国,因此它可以始终解析月,和时区为UTC,所以你不必担心某些时候被跳过或不明确的。
Note that I'm setting the locale to US so it can always parse "Nov", and the time zone to UTC so you don't need to worry about certain times being skipped or ambiguous.
这篇关于如何日期和时间换算成12小时格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!