[英]converting date timezone format in java
在下面的代碼中編寫了嘗試從雙引號中的值轉換日期時間的代碼,但由於解析異常而失敗。 請指教
public static void main(String args[]) {
try {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z");
Date date = format.parse("2016-02-03 10:39:29.099545 -8:00");
} catch (ParseException pe) {
// TODO: Add catch code
pe.printStackTrace();
}
}
這將失敗,解析異常。
更進一步,我的最終輸出應類似於以下格式:2016-01-26T12:07:41-08:00
時區的表示形式與字符串“ -8:00”不對應。 您可以使用三種類型的時區表示形式:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S XXX");
Date date = format.parse("2016-02-03 10:39:29.099545 -08:00");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z");
Date date = format.parse("2016-02-03 10:39:29.099545 -0800");
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S zzz");
Date date = format.parse("2016-02-03 10:39:29.099545 GMT-08:00");
查看SimpleDateFormat文檔
要將日期從日期轉換為所需的字符串,請使用以下格式:
DateFormat format2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
String str = format2.format(date);
但是對於ISO 8601時區標准,請從SimpleDateFormat文檔中考慮:
對於格式化,如果距GMT的偏移值為0,則生成“ Z”
要將日期格式化為ISO 8601 ,可以使用以下代碼段。
// pre Java 8
TimeZone timeZone = TimeZone.getTimeZone("PST");
GregorianCalendar cal = new GregorianCalendar(timeZone);
cal.set(2016, 1, 26, 12, 7, 41);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
sdf.setTimeZone(timeZone);
System.out.println(sdf.format(cal.getTime()));
SimpleDateFormat的格式化規則。
// Java 8
LocalDateTime dateTime = LocalDateTime.of(2016, 1, 26, 12, 7, 41);
ZonedDateTime of = ZonedDateTime.of(dateTime, ZoneId.of("-0800"));
DateTimeFormatter pattern = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
String format = pattern.format(of);
System.out.println(format);
DateTimeFormatter的 Javadoc。
兩個片段的輸出
2016-02-26T12:07:41-0800
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.