2015-09-25 80 views
3

我嘗試使用SimpleDateFormat格式化時間戳,也是我嘗試使用相同的格式來解析這種格式的日期:SimpleDateFormat的對稱格式/解析

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, YYYY 'at' hh:mma z"); 
GregorianCalendar cal = new GregorianCalendar(Locale.US); 
sdf.setTimeZone(cal.getTimeZone()) 

sdf.parse(sdf.format(1435271907000L)).getTime() == 1435271907000L 

最後一個表達式是假的,實際的結果是1419806280000L

那麼怎麼可能才達到對稱dateTimeFormat解析/格式化的行爲嗎?

+0

你能解釋一下你使用週年'YYYY'和爲什麼剝離秒部分?這兩件事你不能達到同樣的結果...... – Codebender

回答

1

首先出現在格式模式沒有秒,讓你的約會對象的秒將被初始化爲0。第二:YYYY is different from yyyy

ss添加到您的模式並將YYYY更改爲yyyy

SimpleDateFormat sdf = new SimpleDateFormat("MMM d ss, yyyy 'at' hh:mma z"); 

String f = sdf.format(1435271907000L); 
Date d = sdf.parse(f); 

System.out.println(d.getTime() == 1435271907000L); 

注意它也將打印false時間與毫秒> 0(例如1435271907001L)。如果您需要毫秒精度,那麼您還需要將毫秒SSS添加到您的模式。通過修正MMM和HH的情況下

SimpleDateFormat sdf = new SimpleDateFormat("MMM d ss SSS, yyyy 'at' hh:mma z"); 
0

嘗試THI,

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy 'at' HH:mm:ss.a`Z`"); 
GregorianCalendar cal = new GregorianCalendar(Locale.US); 
sdf.setTimeZone(cal.getTimeZone()) 
sdf.parse(sdf.format(1435271907000L)).getTime() == 1435271907000L 

我希望這會工作。