[java] Get Date Object In UTC format in Java

I have written following code. I want to get Date object in UTC format.

I am able to get expected date string in UTC using SimpleDateFormat. But using same SimpleDateFormat object, I am not able to get object in UTC format. It is returning object with IST format.

After searching, I found that Date object doesn't store timestamp info.

How can I get date object in UTC format ?

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class dddd {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println("Input - "+1393572325000L);
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date= new Date(1393572325000L);  
        String dateString = formatter.format(date);

        System.out.println("Converted UTC TIME (using Format method) : "+dateString);

        Date date2 =null;
        try {
            date2 = formatter.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }


        System.out.println("Parsed Date Object (using Parse method) : "+date2);

        System.out.println("Expected Date Object : Fri Feb 28 07:25:25 UTC 2014");

    }

}

This prints following output :

Input - 1393572325000
Converted UTC TIME (using Format method) : 2014-02-28 07:25:25
Parsed Date Object (using Parse method) : Fri Feb 28 12:55:25 IST 2014
Expected Date Object : Fri Feb 28 07:25:25 UTC 2014

This question is related to java simpledateformat

The answer is


You can subtract the time zone difference from now.

final Calendar calendar  = Calendar.getInstance();
final int      utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long     tempDate  = new Date().getTime();

return new Date(tempDate - utcOffset);

final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));

A Date doesn't have any time zone. What you're seeing is only the formatting of the date by the Date.toString() method, which uses your local timezone, always, to transform the timezone-agnostic date into a String that you can understand.

If you want to display the timezone-agnostic date as a string using the UTC timezone, then use a SimpleDateFormat with the UTC timezone (as you're already doing in your question).

In other terms, the timezone is not a property of the date. It's a property of the format used to transform the date into a string.


In java 8 , It's really easy to get timestamp in UTC by using java 8 java.time.Instant library :

Instant.now();

That few word of code will return the UTC Timestamp.


tl;dr

Instant.ofEpochMilli ( 1_393_572_325_000L )
       .toString()

2014-02-28T07:25:25Z

Details

(a) You seem be confused as to what a Date is. As the answer by JB Nizet said, a Date tracks the number of milliseconds since the Unix epoch (first moment of 1970) in the UTC time zone (that is, with no time zone offset). So a Date has no time zone. And it has no "format". We create string representations from a Date's value, but the Date itself is not a String and has no String.

(b) You refer to a "UTC format". UTC is not a format, not I have heard of. UTC (Coordinated Universal Time) is the origin point of time zones. Time zones east of the Royal Observatory in Greenwich, London are some number of hours & minutes ahead of UTC. Westward time zones are behind UTC.

You seem to be referring to ISO 8601 formatted strings. You are using the optional format, omitting (1) the T from the middle, and (2) the offset-from-UTC at the end. Unless presenting the string to a user in the user interface of your app, I suggest you generally stick with the usual format:

  • 2014-02-27T23:03:14+05:30
  • 2014-02-27T23:03:14Z ('Z' for Zulu, or UTC, with an offset of +00:00)

(c) Avoid the 3 or 4 letter time zone codes. They are neither standardized nor unique. "IST" for example can mean either Indian Standard Time or Irish Standard Time.

(d) Put some effort into searching StackOverflow before posting. You would have found all your answers.

(e) Avoid the java.util.Date & Calendar classes bundled with Java. They are notoriously troublesome. Use either the Joda-Time library or Java 8’s new java.time package (inspired by Joda-Time, defined by JSR 310).

java.time

The java.time classes use standard ISO 8601 formats by default when parsing and generating strings.

OffsetDateTime odt = OffsetDateTime.parse( "2014-02-27T23:03:14+05:30" ); 
Instant instant = Instant.parse( "2014-02-27T23:03:14Z" );

Parse your count of milliseconds since the epoch of first moment of 1970 in UTC.

Instant instant = Instant.ofEpochMilli ( 1_393_572_325_000L );

instant.toString(): 2014-02-28T07:25:25Z

Adjust that Instant into a desired time zone.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

zdt.toString(): 2014-02-28T02:25:25-05:00[America/Montreal]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

Joda-Time uses ISO 8601 as its defaults.

A Joda-Time DateTime object knows its on assigned time zone, unlike a java.util.Date object.

Generally better to specify a time zone explicitly rather than rely on default time zone.

Example Code

long input = 1393572325000L;
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );

DateTimeZone timeZoneIndia = DateTimeZone.forID( "Asia/Kolkata" );
DateTimeZone timeZoneIreland = DateTimeZone.forID( "Europe/Dublin" );

DateTime dateTimeIndia = dateTimeUtc.withZone( timeZoneIndia );
DateTime dateTimeIreland = dateTimeIndia.withZone( timeZoneIreland );

// Use a formatter to create a String representation. The formatter can adjust time zone if you so desire.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FM" ).withLocale( Locale.CANADA_FRENCH ).withZone( DateTimeZone.forID( "America/Montreal" ) );
String output = formatter.print( dateTimeIreland );

Dump to console…

// All three of these date-time objects represent the *same* moment in the timeline of the Universe.
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeIndia: " + dateTimeIndia );
System.out.println( "dateTimeIreland: " + dateTimeIreland );

System.out.println( "output for Montréal: " + output );

When run…

dateTimeUtc: 2014-02-28T07:25:25.000Z
dateTimeIndia: 2014-02-28T12:55:25.000+05:30
dateTimeIreland: 2014-02-28T07:25:25.000Z
output for Montréal: vendredi 28 février 2014 02:25:25

Actually, java.util.Date does have a time zone. That time zone is assigned deep in its source code. Yet the class ignores that time zone for most practical purposes. And its toString method applies the JVM’s current default time zone rather than that internal time zone. Confusing? Yes. This is one of many reasons to avoid the old java.util.Date/.Calendar classes. Use java.time and/or Joda-Time instead.