Search code examples
javautcepoch

Getting the millis since EPOCH of an UTC date returning wrong results?


I understand that Date.getTime() in Java will return the millis since EPOCH, considering the Date as a UTC Date.

On Java 6, I have a Date, on which if I execute Date.getTime(), it returns the millis since EPOCH, considering the Date is in PDT timezone. (The server on which I am running the code is configured in the PDT time.)

I want the program to consider it a UTC date and return the milli seconds since EPOCH.

Following is my code snippet and the output:

 logger.debug("Date: " + someDate);
 logger.debug("someDate in millis): " + someDate.getTime());

 Output:                                                                                                         
 Date: 2016-08-19 12:04:56.993
 someDate in millis: 1471633496993 //This is time since EPOCH for 2016-08-19 12:04:56.993 PDT

whereas I want it to return the millis as 1471608296993 (1471608296993 is millis since EPOCH for UTC Date: 2016-08-19 12:04:56.993)

In short I want to get the millis since EPOCH, irrespective of the local timezone, which in my case is PDT.

Please help.


Solution

  • Using the information from this answer to this question, I was able to come up with code that will correctly parse your String as a datetime in UTC. The trick is to use a SimpleDateFormat object to parse the String before creating the Date object:

    String strDate = "2016-08-19 12:04:56.993";
    SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = isoFormat.parse(strDate);
    System.out.println(date);
    System.out.println(date.getTime());
    

    Output:

    Fri Aug 19 08:04:56 EDT 2016
    1471608296993