Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Local time to UTC and vice versa

Tags:

java

android

time

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?

like image 636
Mew Avatar asked May 23 '16 11:05

Mew


People also ask

What is UTC time format?

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.

How do I convert UTC to local time in Excel?

(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.

How do you convert local time to UTC in flutter?

To convert local time to UTC time, we the toUtc() method.

How do I convert local time to UTC?

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.


1 Answers

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 } 
like image 168
Mew Avatar answered Oct 04 '22 01:10

Mew