Convert Local time to UTC and vice versa

65,233

Solution 1

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
}

Solution 2

A simplified and condensed version of the accepted answer:

public static Date dateFromUTC(Date date){
    return new Date(date.getTime() + Calendar.getInstance().getTimeZone().getOffset(new Date().getTime()));
}

public static Date dateToUTC(Date date){
    return new Date(date.getTime() - Calendar.getInstance().getTimeZone().getOffset(date.getTime()));
}

Solution 3

Try this:
//convert to UTC to Local format

 public Date getUTCToLocalDate(String date) {
            Date inputDate = new Date();
            if (date != null && !date.isEmpty()) {
                @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
                simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                try {
                    inputDate = simpleDateFormat.parse(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            return inputDate;
        }  

//convert Local Date to UTC

public String getLocalToUTCDate(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date time = calendar.getTime();
    @SuppressLint("SimpleDateFormat") SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
    outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
    return outputFmt.format(time);
}

Solution 4

tl;dr

ZoneId z = ZoneId.systemDefault() ;  // Or, ZoneId.of( "Africa/Tunis" ) 
ZonedDateTime zdt = ZonedDateTime.now( z ) ;  // Capture current moment as seen in a particular time zone.
Instant instant = zdt.toInstant() ;  // Adjust to UTC, an offset of zero hours-minutes-seconds.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;  // Make an `OffsetDateTime` object to exchange with the database.
myPreparedStatement.setObject( … , odt ) ;  // Write moment to database column of a type akin to the SQL standard type `TIMESTAMP WITH TIME ZONE`.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;  // Retrieve a moment from database.
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;  // Adjust into a particular tim zone. Same moment, different wall-clock time.

java.time

The modern approach uses the java.time;classes that years ago supplanted the terrible date-time classes such as Date and Calendar.

Capture the current moment as seen in UTC.

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;

Store in a database using a driver complaint with JDBC 4.2 or later.

myPreparedStatement( … , odt ) ;

Retrieve from database.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

Adjust into a time zone.

ZoneId z = ZoneId.systemDefault() ;
ZonedDateTime zdt = odt.atZoneSameInstant( z ) ;

Generate text to present to user.

DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( Locale.getDefault() ) ;
String output = zdt.format( f ) ;

An implementation of java.time is built into Android 26+. For earlier Android, the latest tooling brings most of the functionality via “API desugaring”. If that does not work for you, use the ThreeTenABP library to get most of the java.time functionality that was back-ported to Java 6 and Java 7 in the ThreeTen-Backport project.

Solution 5

you may try something like this to insert into DB:

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

This opt from ur comment:

OUTPUT:

1:43 PM Mon UTC

For this, -> convert it again and display in the device's time

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

OUTPUT:

7:30 PM Mon GMT+05:30

U may display like this.

Share:
65,233
Mew
Author by

Mew

Updated on February 19, 2022

Comments

  • Mew
    Mew about 2 years

    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?