2

I am trying to convert a date into milliseconds with the following code:

    GregorianCalendar gc = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
    gc.clear();
    gc.set(1900, 1, 1);

    long left = gc.getTimeInMillis();

I get left=-2206310400000, but when I check here, I should get -2208988800000.

What am I doing wrong?

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453

2 Answers2

3

You're using 1 for the month number, which means February.

You mean

gc.set(1900, 0, 1);

From the docs:

month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

Yes, the Java date/time API is broken. If you're doing any significant amount of work in dates/times, I'd suggest you use Joda Time instead.

long left = new DateTime(1900, 1, 1, 0, 0, DateTimeZone.UTC).getMillis();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        long epochMillis = OffsetDateTime.of(1900, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC)
                            .toInstant()
                            .toEpochMilli();

        System.out.println(epochMillis);
    }
}

Output:

-2208988800000

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110