經歷了一個星期的經歷了這麼多的例子,並從Java日期, 到日曆,以喬達。我決定尋求其他來源的幫助。Joda DateTime ,,格式化和Mysql時間戳
問題:
我們的表有兩個字段日期(時間戳),和TZ(字符串)。這個想法是在時間戳和時區中存儲用戶的UTC的UTC時間,當然,你明白了。所以基本上 我們認爲UTC,並與轉化爲他們的 時區在前端時出示的用戶(即,使用table.TZ值店)
另一個要求是使用適當的對象(日期,DateTime什麼的)。 而不是傳遞日期的字符串表示。最好是 是一個有效的Long,它將被MySQL正確轉換,而不會有 在我們的查詢中使用FROM_UNIXTIME mysql函數。我們使用
代碼:
public DateTime convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withLocale(l);
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
System.out.println(formatter.print(dstDateTime));
System.out.println(formatter.parseDateTime(dstDateTime.toString()));
return formatter.parseDateTime(formatter.print(dstDateTime));
}
串組輸出正是我們所需要的(即UTC時間,2013年8月23日18時19分12秒), 但formatter.parseDateTime(dstDateTime.toString()
與以下崩潰 錯誤。大概是因爲UTC時區的獨立信息,並milleseconds?:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2013-08- 23T18:19:12.515Z" is malformed at "T18:19:12.515Z"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:873)
at com.example.business.rate.RateDeck.convertTimezone(RateDeck.java:75)
at com.example.business.rate.RateDeck.WriteData(RateDeck.java:143)
at com.example.business.rate.RateDeck.main(RateDeck.java:64)
搜索引擎豐富的問題:
如何格式化爲UTC日期時間約達。
PS我的第一個SO貼子,感覺不錯? :)
由於事先
新的固定的版本:
public Timestamp convertTimezone(LocalDateTime date, DateTimeZone srcTZ, DateTimeZone dstTZ, Locale l) {
DateTime srcDateTime = date.toDateTime(srcTZ);
DateTime dstDateTime = srcDateTime.toDateTime(dstTZ);
return new Timestamp(dstDateTime.getMillis());
}
尼克。
感謝但不是格式化負責重新塑造代表無論?我不確定我遵循:S。我看到你在說什麼,將格式化器改爲「yyyy-MM-dd'T'HH:mm:ss.SSSZZ」,停止崩潰並輸出正確的UTC「2013-08-23T21:28:04.290 + 00: 00「,但是,我們需要DateTime格式爲」yyyy-MM-dd HH:mm:ss「。 –
格式化程序使用'formatter.prin(theDateTimeToFormat)'格式化DateTime作爲字符串,當你這樣做時。但是你沒有。您調用DateTime.toString()來將DateTime轉換爲String。我真的不明白你想用這個System.out.println語句來做什麼。 –
DateTime沒有任何格式。這是毫秒數,以及時區標識符。只有這樣。當您將此值轉換爲字符串時,您可以選擇使用哪種格式,這要感謝DateTimeFormatter。 toString()方法使用ISO8601格式將DateTime轉換爲字符串。 –