Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Epoch is not epoch if do a new Date(0L). Why?

Tags:

java

date

epoch

My problem is pretty straigtforward explained :

if I do this :

public class Main {

public static void main(String[] args) throws Exception {
        Date d = new Date(0L );
        System.out.println(d);
}

}

I get the following output : Thu Jan 01 01:00:00 CET 1970

According to the doc, I was expecting : Thu Jan 01 00:00:00 CET 1970

I would like was going wrong...

EDIT : Indeed, I read the doc too fast. I should have Thu Jan 01 00:00:00 GMT 1970

So, how can I force the use of GMT, and ignore all local time ?

Edit, Solution :

public static void main(String[] args) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("H:m:s:S");
SimpleTimeZone tz = new SimpleTimeZone(0,"ID");
sdf.setTimeZone(tz) ;
Date d = new Date(0L );
System.out.println( sdf.format(d));
}
like image 502
Antoine Claval Avatar asked Dec 13 '22 23:12

Antoine Claval


1 Answers

The Epoch is defined as 00:00:00 on 1970-1-1 UTC. Since CET is UTC+1, it's equal to 1AM your time.

If you look at the Date(long) constructor, you'll see that it expects the value to be the number of milliseconds since the epoch, UTC:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

Regarding your desire to force GMT instead of your local time zone: In short, the Date instance always uses GMT. If you just want to format the output String so that it uses GMT have a the DateFormat class, and specifically, its setTimeZone() method.

like image 76
Jason Nichols Avatar answered Dec 24 '22 07:12

Jason Nichols