Mew
Mew

Reputation: 1142

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?

Upvotes: 35

Views: 87388

Answers (8)

Basil Bourque
Basil Bourque

Reputation: 338181

tl;dr

Current moment:

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.

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.

Upvotes: 11

Chris Stillwell
Chris Stillwell

Reputation: 10547

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

Upvotes: 31

raman rayat
raman rayat

Reputation: 414

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

Upvotes: 2

Neelesh Atale
Neelesh Atale

Reputation: 536

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

Upvotes: 16

SANAT
SANAT

Reputation: 9257

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

Upvotes: 0

Mew
Mew

Reputation: 1142

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
}

Upvotes: 39

User Learning
User Learning

Reputation: 3473

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.

Upvotes: 3

der_Fidelis
der_Fidelis

Reputation: 1515

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.

Upvotes: 2

Related Questions