Java Date toInstant method return a different date?

Viewed 313

Here is my test code, date of 1111-11-11 to instant method result is 1111-11-17

jshell> new Date(-789,10,11)
$8 ==> Sat Nov 11 00:00:00 JST 1111

jshell> new Date(-789,10,11).toInstant();
$9 ==> 1111-11-17T15:00:00Z
1 Answers

I recommend you switch from the outdated and error-prone legacy date-time API to the modern date-time API.

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

public class Main {
    public static void main(String args[]) {
        OffsetDateTime odt = OffsetDateTime.of(1111, 11, 11, 0, 0, 0, 0, ZoneOffset.UTC);
        Instant instant = odt.toInstant();
        System.out.println(instant);
    }
}

Output:

1111-11-11T00:00:00Z

How to do it using the legacy date-time API:

Note that the dates before 1582-10-15 are handled as Julian calendar. Check https://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html for more details. Please also check https://stackoverflow.com/a/23460471/10819573 which I've referred to write the following code:

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class Main {
    public static void main(String args[]) throws ParseException {
        GregorianCalendar proleptic = new GregorianCalendar();
        proleptic.clear();
        proleptic.setGregorianChange(new Date(Long.MIN_VALUE));
        proleptic.set(Calendar.DAY_OF_MONTH, 11);
        proleptic.set(Calendar.MONTH, Calendar.NOVEMBER);
        proleptic.set(Calendar.YEAR, 1111);
        System.out.println(proleptic.toInstant());
    }
}

Output:

1111-11-11T00:00:00Z
Related