2016-05-23 125 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())); 
} 
相关问题