我有特定的情況,我必須將日期字段轉換爲GMT時間,然後將其轉換爲特定的字符串格式。將GMT時間轉換爲特定的字符串格式
這給GMT時間:
public static void main(String[] args) {
Date rightNow = Calendar.getInstance().getTime();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(rightNow));
String gmtDate=gmtFormat.format(rightNow);
}
現在我需要的是GMT時間轉換爲字符串格式yyyy-MM-ddTHH:mm:ssZ
在我的時區實例當前時間是17:10:00
,在GMT 15:10:00
所以這意味着最終的輸出應2017-08-07T15:10:00Z
我嘗試這樣的代碼來添加:
String pattern = "yyyy-MM-ddTHH:mm:ssZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(gmtDate);
System.out.println(date);
但是我當然得到異常,因爲字符串不能像這樣轉換,但我需要類似的東西。
你*有*使用舊的日期/時間API? java.time包很多,更好。除此之外,還不清楚你得到什麼異常或在哪裏... –
嗨我在這條線上得到異常:SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); (Unknown Source) \t at java.text.SimpleDateFormat.initialize(Unknown Source) – Dejan
Right,你有沒有調查過?基本上你的模式已經壞了 - 你需要引用'T'和'Z'。 –