简体   繁体   中英

Java SimpleDateFormat won't parse a specific time in 2013 with setLenient(false)

Ok so I have a very specific bug that I wish to know if anyone knows why this is happening. Here's the code

public static void main(String[] args) {
  String time = "2013-03-10 02:59:26";
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  formatter.setLenient(false);
  Date modDate;
  try {
    System.out.println("Date String: " + time);
    modDate = formatter.parse(time);
  } catch (ParseException e) {
    System.out.println("Date String: " + time);
  e.printStackTrace();
}

So this code throws an unparseable error ONLY when the year is 2013 and the month is march (03) and the day is the 10th, and the time is 02 hours and the minutes are anywhere in the 50's. I'm parsing some log files that log by the millisecond so there's a lot in this time frame, and it throws an unparsable error only for those ten minutes in the log files for some reason. I've tried looking into everything and it looks like a real date to me. One thing that does fix it is setLenient(true); But I'd like to know why with setLenient(false) it fails? (Java 7 on Windows 7)

Depending on your default time zone, that instant may not exist, due the the "spring ahead" of daylight savings time.

Areas in the US that follow daylight saving start in the morning of the second Sunday in March, and the hour between 2 AM and 3 AM, local time, is skipped. Because clocks change from 01:59:59 to 03:00:00, there is no 02:59:59 on that day.

The strings in your log file represent instants in time; internally, those instants are stored as the number of milliseconds since 1970, UTC. That's the value you want to reconstruct when you parse the string. (A Date instance is just a wrapper around this number, and doesn't carry any information about local time zone, etc.) You should be able to recover the original date by setting your parser with the same time zone that was used when formatting the date when logging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM