2012-07-22 103 views
0

我有几个日期的字符串:SimpleDateFormat的解析函数改变格式

[20-JUL-2012 5:11:36670 UTC PM,20-JUL-2012 5:11:36683 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)) ; 

输出:Fri Jul 20 06:11:36 BST 2012

我需要的输出为20-Jul-2012 5:11:36,670 UTC PM

我是否需要在SimpleDateFormat中设置LOCALE以使其不具有不同的输出?

+0

possibl e [从String java提取日期]的副本(http://stackoverflow.com/questions/11599591/extract-date-from-string-java) – 2012-07-22 12:32:10

+0

这是同一个问题吗?如果没有,请在这里编辑这一个,以清楚地区别于您的其他问题...或几天前您问过的问题:http://stackoverflow.com/questions/11507845/error-using-simpledateformat – 2012-07-22 12:32:59

回答

2

您需要设置时区,但更重要的是,你只需要实际使用的格式来格式化日期:

Date date = format2.parse(...); 
String formattedDate = format2.format(date); 
System.out.println(formattedDate); 

你的代码所做的是:

Date date = format2.parse(...); 
System.out.println(date.toString()); 

我虽然并不真正理解将字符串解析为日期,然后使用完全相同的格式显示日期,但(除了验证字符串确实是有效日期,但是可以简单地重新使用原始字符串) 。

1

你有两个小问题:

  1. 使用hh的小时,不HHH是“一天中的小时(0-23),因此无法与上午/下午的标记a一起正常工作。您的两个示例日期字符串将解析为AM,而不是PM。
  2. 您正在使用SimpleDateFormat解析字符串,但不进行格式化使用format2.format(format2.parse(entry.getValue().toString())

这里有一个完整的例子:。

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); 

结果:

20-Jul-2012 05:11:36,670 UTC PM