将本地时间转换为UTC,反之亦然 [英] Convert Local time to UTC and vice versa
本文介绍了将本地时间转换为UTC,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究Android应用程序,我希望将本地时间(设备时间)转换为UTC并将其保存在数据库中。从数据库中检索后,我必须再次转换它并显示在设备的时区。任何人都可以建议如何在Java中这样做吗?
I'm working on Android application, and I want to convert local time (device time) into UTC and save it in database. After retrieving it from database I have to convert it again and display in the device's time zone. Can anyone suggest how to do this in Java?
推荐答案
我使用这两种方法将本地时间转换为GMT / UTC,反之亦然这对我没有任何问题,工作正常。
I converted local time to GMT/UTC and vice versa using these two methods and this works fine without any problem for me.
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日期传递给此方法:
pass the GMT/UTC date which you want to convert into device local time to this method:
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
}
这篇关于将本地时间转换为UTC,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文