Java, convert date to string and return the date that generated the error

I tried to convert date to string and then back to date But I find that the last date is different from the original date. What gives it?

//1975-06-20
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR,1975);
    cal.set(Calendar.MONTH,5);
    cal.set(Calendar.DAY_OF_MONTH,20);
    cal.set(Calendar.HOUR,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.SECOND,0);
    System.out.println(cal);

    Date originalDate = cal.getTime();
    System.out.println("Date 1: " + originalDate.toString());

    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
    Date date = sdf.parse(originalDate.toString());
    System.out.println("Date 2: " + date.toString());

The output of the above code is:

cal: java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Singapore",offset=28800000,dstSavings=0,useDaylight=false,transitions=9,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=1975,MONTH=5,WEEK_OF_YEAR=26,WEEK_OF_MONTH=5,DAY_OF_MONTH=20,DAY_OF_YEAR=179,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=4,AM_PM=1,HOUR=0,HOUR_OF_DAY=16,MINUTE=0,SECOND=0,MILLISECOND=333,ZONE_OFFSET=28800000,DST_OFFSET=0]
Date 1: Fri Jun 20 12:00:00 SGT 1975
Date 2: Fri Jun 20 11:30:00 SGT 1975

Solution

It may be due to the change in Singapore's time zone in 1982 (30 minutes)

@L_ 404_ 0@

When parsing the date, simpledateformat takes Sgt as UTC 8 and converts it to UTC 7.5, that is, Sgt before 1982. Therefore, the date is closed for 30 minutes

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>