[英]SimpleDateFormat parse function changing the format
I have a String with several dates: 我有一个带有几个日期的字符串:
[20-Jul-2012 5:11:36,670 UTC PM, 20-Jul-2012 5:11:36,683 UTC PM] [2012年7月20日5:11:36,670 UTC PM,2012年7月20日5:11:36,683 UTC PM]
ParsePosition parsePos = new ParsePosition(1);
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss,SSS z a");
System.out.println(format2.parse(entry.getValue().toString(), parsePos)) ;
Output : Fri Jul 20 06:11:36 BST 2012
输出:
Fri Jul 20 06:11:36 BST 2012
I need the output to be 20-Jul-2012 5:11:36,670 UTC PM
. 我需要输出为
20-Jul-2012 5:11:36,670 UTC PM
。
Do I need to set a LOCALE in the SimpleDateFormat
to not have a different output? 我是否需要在
SimpleDateFormat
中将LOCALE设置为没有其他输出?
You need to set the time zone, but more importantly, you simply need to actually use the format to format the date: 您需要设置时区,但更重要的是,您只需要实际使用格式来格式化日期即可:
Date date = format2.parse(...);
String formattedDate = format2.format(date);
System.out.println(formattedDate);
What your code does is: 您的代码的作用是:
Date date = format2.parse(...);
System.out.println(date.toString());
I don't really understand the point in parsing a string to a date, and then displaying the date using the exact same format, though (except to validate that the String is indeed a valid date, but then you could simply reuse the original string). 我真的不明白将字符串解析为日期,然后使用完全相同的格式显示日期的意义,不过(除了要确认String确实是有效日期,否则您可以简单地重用原始字符串)。
You've got two small problems: 您有两个小问题:
hh
for the hour, not HH
. hh
,而不是HH
。 H
is "Hour in day (0-23), and so will not work correctly with a
, the AM/PM marker. Your two example date strings will parse to AM, not PM. H
是“在(0-23)小时,因此不会与正常工作a
中,AM / PM标记。你的两个示例日期字符串将解析到AM,PM没有。 format2.format(format2.parse(entry.getValue().toString())
. format2.format(format2.parse(entry.getValue().toString())
。 Here's a complete example: 这是一个完整的示例:
SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss,SSS z a");
String input = "20-Jul-2012 5:11:36,670 UTC PM";
Date date = format.parse(input);
String output = format.format(date);
System.out.println(output);
Result: 结果:
20-Jul-2012 05:11:36,670 UTC PM
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.