Java, converting Date to String and back produced wrong Date

为君一笑 提交于 2019-12-10 20:37:30

问题


I am trying to convert a Date to String and then back again to Date. However I found out that the final date is different from the original date, what gives?

    //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 from 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

回答1:


Probably because of the timezone change in Singapore on 1982 (+ 30 minutes).

http://www.timeanddate.com/worldclock/timezone.html?n=236&syear=1980

The SimpleDateFormat take the SGT as UTC+8 when parsing the date, and convert it to UTC+7.5, which is the SGT before 1982. Hence the date is off by 30 minutes.




回答2:


are you sure you pasted the code right?

Date date = DateFormat.format(originalDate.toString(), "EEE MMM dd HH:mm:ss zzz yyyy");

seems problematic: there is no method with the signature Date DateFormat.format(String, String) as far as I know



来源:https://stackoverflow.com/questions/11221703/java-converting-date-to-string-and-back-produced-wrong-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!