2016-05-23 205 views
3

我正在開發Android應用程序,並且希望將本地時間(設備時間)轉換爲UTC並將其保存到數據庫中。從數據庫中檢索後,我必須再次將其轉換並顯示在設備的時區中。任何人都可以建議如何在Java中做到這一點?將本地時間轉換爲UTC,反之亦然

+0

改進問題 – AlBlue

回答

14

我使用這兩種方法將當地時間轉換爲GMT/UTC,反之亦然,這對我來說沒問題。

public static Date localToGMT() { 
    Date date = new Date(); 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); 
    sdf.setTimeZone(TimeZone.getTimeZone("UTC")); 
    Date gmt = new Date(sdf.format(date)); 
    return gmt; 
} 

傳遞要轉化爲設備本地時間可以到本方法的GMT/UTC日期:

public static Date gmttoLocalDate(Date date) { 

    String timeZone = Calendar.getInstance().getTimeZone().getID(); 
    Date local = new Date(date.getTime() + TimeZone.getTimeZone(timeZone).getOffset(date.getTime())); 
    return local 
} 
+0

謝謝。其工作正常 – appy

+0

新日期(字符串日期)已棄用。你不應該使用它! –

0

Time.getCurrentTimezone()

將讓你的時區和

Calendar c = Calendar.getInstance(); int seconds = c.get(Calendar.SECOND)

將讓你的時間在UTC在幾秒鐘。當然,你可以改變它的價值來獲得它在另一個單位。

+0

讓我們說,如果今天的日期是5:34 PM星期一(IST),那麼我怎樣才能得到它像下午12:04星期一(UTC) – Dyo

+0

您是否確實有時間訪問需要轉換或做的時間對象你只是有一個字符串? –

+0

我只是有一個字符串 – Dyo

1

,你可以嘗試這樣的事情插入到DB:

SimpleDateFormat f = new SimpleDateFormat("h:mm a E zz"); 
    f.setTimeZone(TimeZone.getTimeZone("UTC")); 
    System.out.println(f.format(new Date())); 
    String dd = f.format(new Date()); 

此選擇從烏爾評論:

OUTPUT:

下午1:43週一UTC

爲此, - > convert它再次在設備的時間顯示

UPDATE:

String dd = f.format(new Date()); 

     Date date = null; 
     DateFormat sdf = new SimpleDateFormat("h:mm a E zz"); 
     try { 
      date = sdf.parse(dd); 
     }catch (Exception e){ 

     } 
     sdf.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata")); 
     System.out.println(sdf.format(date)); 

OUTPUT:

7:30 PM週一GMT + 05:30

ü可能會這樣顯示。

+0

它試圖再次轉換它時顯示空指針異常 – Dyo

+0

不可能,我已經嘗試過,並且工作良好。你可以給我堆棧跟蹤你的應用程序 –

+0

我剛剛初始化日期=新日期()和它的工作很好謝謝 – Dyo

0

獲取當前UTC:

public String getCurrentUTC(){ 
     Date time = Calendar.getInstance().getTime(); 
     SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     outputFmt.setTimeZone(TimeZone.getTimeZone("UTC")); 
     return outputFmt.format(time); 
} 
1

公認的簡化版本回答:

public static Date dateFromUTC(Date date){ 
    return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(date.getTime())); 
} 

public static Date dateToUTC(Date date){ 
    return new Date(date.getTime() - Calendar.getInstance().getTimeZone().getOffset(date.getTime())); 
} 
相關問題