'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 1:[1]

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 2:[2]

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 3:[3]

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 4:[4]

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.

Solution 5:[5]

Time.getCurrentTimezone()

will get you the timezone and

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

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

Solution 6:[6]

try this one

DateFormat formatterIST = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formatterIST.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
        Date dateobj = new Date();
        Date date = formatterIST.parse(formatterIST.format(dateobj));
        System.out.println(formatterIST.format(date));

        DateFormat formatterUTC = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formatterUTC.setTimeZone(TimeZone.getTimeZone("UTC")); // UTC timezone
        System.out.println(formatterUTC.format(date));

Solution 7:[7]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MJBZA
Solution 2 Neelesh Atale
Solution 3
Solution 4
Solution 5 der_Fidelis
Solution 6 raman rayat
Solution 7 SANAT