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?
Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.
(2) The formula =A2 + (9 / 24) will return a decimal number. For converting the decimal number to time, please select the decimal number, and click Home > Number Format > Time.
To convert local time to UTC time, we the toUtc() method.
Add the local time offset to the UTC time. For example, if your local time offset is -5:00, and if the UTC time is shown as 11:00, add -5 to 11. The time setting when adjusted for offset is 06:00 (6:00 A.M.). Note The date also follows UTC format.
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; }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With