簡體   English   中英

如何使用“ DateFormat”將String轉換為Date對象?

[英]How to convert String into Date object using “DateFormat”?

我正在嘗試通過使用以下代碼將計算機的日期/時間轉換為GMT時區:

DateFormat gmtFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Orginal Date : " + new Date());
String s= gmtFormat.format(new Date());
System.out.println("Converted Date As String: "+ s);
System.out.println("Converted Date As date object : " + gmtFormat.parse(s));

上面的代碼輸出:

Orginal Date : Mon Apr 21 21:04:06 AST 2014
Converted Date As String: Mon Apr 21 18:04:06 GMT 2014
Converted Date As date object : Mon Apr 21 21:04:06 AST 2014

但是,當我通過使用parse函數將“轉換為字符串形式的日期”解析為“轉換為日期對象的日期對象”時出現問題,但是您會注意到該日期更改為原始日期

為什么會這樣呢?


當我執行以下操作時,問題就解決了:

DateFormat gmtFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Orginal Date : " + new Date());
String s= gmtFormat.format(new Date());
System.out.println("Converted Date As String: "+ s);
// Just I added Local Time Zone Formatand I use it to call parse instead of gmtFormat
DateFormat LocalFormat = new SimpleDateFormat("E MMM dd HH:mm:ss 'GMT' yyyy");
System.out.println("Converted Date As date object : " + LocalFormat.parse(s));

我想知道為什么會這樣>>本地格式如何與解析函數相關? 有誰知道為什么嗎?

DateFormat.parse(String)的返回值是java.util.Date ,它不保留有關時區或語言環境的任何信息。 Date本質上是圍繞long值的包裝對象,該long值表示自格林尼治標准時間1970年1月1日以來的毫秒數。 調用其toString()方法時,默認實現將在本地系統的默認時區中呈現日期。

如果要創建同時存儲時間戳關聯的時區/地區的日期/時間表示,則應創建一個java.util.Calendar對象(使用Calendar.getInstance(...)並為其提供TimeZone和/或Locale ,然后使用Date對象設置與日歷關聯的時間,該對象代表所需的日期/時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM