The task of presenting midnight on May 1, 1921 in the class java.util.Date

I want to introduce midnight on the java.util.Date class. To test this, I print this value and get an unexpected result.

The following code:

Calendar calendar = new GregorianCalendar(1921, 4, 1, 0, 0);
Date date2 = calendar.getTime();
System.out.println(date2);

I get the following output:

Sun May 01 00:20:08 EET 1921

But I expect to get

Sun May 01 00:00:00 EET 1921

What is the reason for this behavior?

I am currently testing my code in the time zone of Europe / Helsinki.

+3
source share
4 answers

Why don't you just check the time zone history for your country? You asked a similar question just a few days ago. Finland had a very strange time zone GMT + 1: 39: 52 until April 30, 1921. From May 1, they switched to GMT + 2: 00 and jumped from 23:59:59 to 00:20:08.

+11

, , -)

public static void main(String[] args) {
    Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("Europe/Helsinki"));
    calendar.set(1921,4, 1, 0, 0);
    Date date2 = calendar.getTime();
    System.out.println("GregorianCalendar: " + date2);

    DateTime c2 = new DateTime(DateTimeZone.forID("Europe/Helsinki")).withYear(1921).
            withMonthOfYear(5).withDayOfMonth(1).withHourOfDay(0). withMinuteOfHour(0).withSecondOfMinute(0).withMillisOfSecond(0);
    System.out.println("Joda: " + c2);
}

GregorianCalendar: Sat Apr 30 23:20:43 CEST 1921
Exception in thread "main" org.joda.time.IllegalFieldValueException: Value 0 for minuteOfHour is not supported: Illegal instant due to time zone offset transition: 1921-05-01T00:00:35.781 (Europe/Helsinki)
    at org.joda.time.chrono.ZonedChronology$ZonedDateTimeField.set(ZonedChronology.java:469)
    at org.joda.time.DateTime.withMinuteOfHour(DateTime.java:1485)
+3

In fact, many time zones give a strange result until October 1979. I suggest you look at Joda's time if you want an accurate historical time zone.

The worst day, apparently, January 1, 1900. Try

Calendar calendar = new GregorianCalendar(1900, 1, 1, 0, 0);
Date date2 = calendar.getTime();
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println("Time in UTC is " + date2);

for (String tz : TimeZone.getAvailableIDs()) {
    TimeZone.setDefault(TimeZone.getTimeZone(tz));
    String dateToString = date2.toString();
    if (dateToString.contains(":00:00")) continue;
    if (dateToString.contains(":30:00")) continue;
    System.out.println(tz + ' ' + dateToString);
}

Until 1900, very few timeshones produce such results (perhaps inaccurate)

+1
source

Make sure jarnbjo is above, will Joda-Time help any of your problems?

Java Date / Time / Calendar libraries are interrupted several times.

0
source

Source: https://habr.com/ru/post/1720830/


All Articles