[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");
        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) {

        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

final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
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.


Instant.ofEpochMilli ( 1_393_572_325_000L )



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


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.


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.

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


That few word of code will return the UTC Timestamp.

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

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with simpledateformat tag:

How to convert an Instant to a date format? Get Date Object In UTC format in Java How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss) How to convert date to string and to date again? Java Convert GMT/UTC to Local time doesn't work as expected Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST SimpleDateFormat parse loses timezone java.text.ParseException: Unparseable date Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss SimpleDateFormat returns 24-hour date: how to get 12-hour date? How to convert date in to yyyy-MM-dd Format? Java String to Date object of the format "yyyy-mm-dd HH:mm:ss" What are the date formats available in SimpleDateFormat class? Get yesterday's date using Date How to format date string in java? Using GregorianCalendar with SimpleDateFormat How to convert a String to a Date using SimpleDateFormat? How to add minutes to my Date How to convert HH:mm:ss.SSS to milliseconds? How can I get current date in Android? What is this date format? 2011-08-12T20:17:46.384Z Convert string to date then format the date Why is Java's SimpleDateFormat not thread-safe? Convert String to Calendar Object in Java Is there a date format to display the day of the week in java? How to parse dates in multiple formats using SimpleDateFormat How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)? Illegal pattern character 'T' when parsing a date string to java.util.Date SimpleDateFormat parsing date with 'Z' literal How to parse month full form string using DateFormat in Java? SimpleDateFormat and locale based format string How to parse a date?