0

Currently I am trying to convert a date calculation from javascript to java, since I want to use it for Android development. So in javascript I was using the method date.valueOf(), which converts the date to the milliseconds that passed since January 1, 1970. In java the method with the same funcionality is called date.getTime(). In the java and javascript documentation the description is exactly the same, but when I am inserting the same date, I am getting two completely different values. For example:

Java getTime()

Date date = new Date(2011, 10, 1);
System.out.println(date.getTime()); //prints: 61278249600000

Javascript valueOf()

const date = new Date(2011, 10, 1);
console.log(date.valueOf()); //prints: 1320102000000

So my questions are:

  • Why is this happening? (or what did I wrong?)
  • How can I correct the code?

It would be awesome if somebody can help me.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
stnieder
  • 15
  • 2
  • 2
    Do not longer use the old java Date API. – Jens Dec 20 '20 at 12:17
  • And how should I then convert the date to milliseconds since January 1, 1970? – stnieder Dec 20 '20 at 12:41
  • Read about the java.time API – Jens Dec 20 '20 at 12:54
  • [Tutorial link](https://docs.oracle.com/javase/tutorial/datetime/) – Ole V.V. Dec 20 '20 at 13:08
  • I recommend that in Java you don’t use `Date`. That class is poorly designed and long outdated. Instead use `LocalDate` and other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Dec 20 '20 at 13:09
  • In Java use `LocalDate.of(2011, Month.NOVEMBER, 1).atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()`. In my time zone, Europe/Copenhagen, it gives the same number as you get in JavaScript, 1 320 102 000 000. The result in other time zones will differ by up to about 13 hours. – Ole V.V. Dec 20 '20 at 15:41

1 Answers1

4

The discrepancy isn't between Java's getTime and JavaScript's valueOf, it's the Java Date constructor. The year parameter is years since 1900. So the equivalent Java code would be:

Date date = new Date(110, 10, 1);
//                   ^−−− 2010 - 1900

This is one of the many reasons not to use the java.util.Date class.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875