我正在尝试将Date
转换为String
,然后再转回Date
。但是我发现最终日期与原始日期不同,是什么给出了?
//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());
以上代码的输出是:
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
答案 0 :(得分:13)
可能是因为1982年新加坡的时区变化(+ 30分钟)。
http://www.timeanddate.com/worldclock/timezone.html?n=236&syear=1980
SimpleDateFormat在解析日期时将SGT视为UTC + 8,并将其转换为UTC + 7.5,即1982年之前的SGT。因此,日期将关闭30分钟。
答案 1 :(得分:0)
你确定你正确粘贴了代码吗?
日期日期= DateFormat.format(originalDate.toString(),“EEE MMM dd HH:mm:ss zzz yyyy”);
似乎有问题:据我所知,没有签名Date DateFormat.format(String,String)的方法