Convert local time to UTC and vice versa

I am working on an Android application and I want to convert the local time (device time) to UTC and store it in the database. Having received it from the database, I have to convert it again and display it in the time zone of the device. Can anyone suggest how to do this in Java?

+4
source share
5 answers

I converted the local time to GMT / UTC and vice versa using these two methods and it works fine without any problems 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 that you want to convert to the local device time for 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
}
+15
source

A simplified and concise version of the accepted answer:

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()));
}
+3

- :

    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());

:

:

1:43 PM Mon UTC

To do this, → convert it again and show during device

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));

CONCLUSION:

7:30 PM Mon GMT + 05: 30

U can be displayed as follows.

+1
source

Time.getCurrentTimezone()

you will get the time zone and

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

You will get the time in UTC in seconds. Of course, you can change the value to get it in another device.

0
source

Get current 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);
}
0
source

All Articles