Search code examples
javaandroidtime

Convert Local time to UTC and vice versa


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?


Solution

  • 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
    }