Search code examples
javadateutc

java.util.Date and the UTC problem


I know this has been a hot topic over the time... but I can't find a suitable answer.

I have the current UTC time in ms, which I need to compare to the current time in my machine (so they should match).

long myUTCtime = .....; // This reflects the UTC time
// myDate is in UTC, ok, I agree
Date myDate = new Date();
// When I use getTime() I get the localtime in ms, although not in UTC! but in DST
long milis = myDate.getTime();
// I get here a 60 minute difference
long difference = milis - myUTCtime;

How can I do this?

Thanks in advance.

EDIT: I don't need the calendar or anything. I'm not showing the information to the user, I just want to use UTC times, and Date is supposed to be ALWAYS in UTC


Solution

  • Date myDate = new Date();
    long milis = myDate.getTime();
    

    should be equivalent to the simpler:

    long milis = System.currentTimeMillis();
    

    Both should return

    the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

    Quick check in my linux box:

    # cat X.java
    public class X { public static void main(String[] args) {
                    System.out.println( (new java.util.Date()).getTime());
                    System.out.println( System.currentTimeMillis());
            } }
    
    # javac X.java ; java X ; perl -e 'print time()*1000'
    1305133124654
    1305133124654
    1305133124000
    

    Perhaps you have an interpretation issue...