SimpleDateFormat not parsing time correctly [duplicate]

♀尐吖头ヾ 提交于 2020-01-16 18:10:07

问题


This is happening with one (probably more) datetime where the time part is totally wrong in a parse.

The code:

import java.text.*;
import java.util.*;

public class TestTimeParse {
    public static void main(String[] args) {
        SimpleDateFormat dateFmt = (SimpleDateFormat) DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.getDefault());
        dateFmt.applyPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        ParsePosition pos = new ParsePosition(0);
        Date date = dateFmt.parse("2018-11-01T18:07:55.6725292Z", pos);
        System.out.println("Text 2018-11-01T18:07:55.6725292Z parses as " + date);
    }
}

The output:

Text 2018-11-01T18:07:55.6725292Z parses as Thu Nov 01 20:00:00 MDT 2018

What is going on for the time component? The hours is wrong and the minutes & seconds are zeroed out.


回答1:


This is one of the problems with the obsolete Date, Calendar and SimpleDateFormat classes. You shouldn't use it, for it's supplanted by the new Date and Time API in Java 8. It is available in the java.time package.

String str = "2018-11-01T18:07:55.6725292Z";
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'";

LocalDateTime ts = LocalDateTime.parse(str, DateTimeFormatter.ofPattern(pattern));
System.out.println("Text 2018-11-01T18:07:55.6725292Z parses as " + ts);

It seems that SimpleDateFormat is only able to read up to three millisecond digits. The parsing process works if one truncates the fraction portion of the date to three digits, i.e. "2018-11-01T18:07:55.672" instead of "2018-11-01T18:07:55.6725292Z", and also changes the according 'S' pattern specifiers, i.e. "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'".



来源:https://stackoverflow.com/questions/54635330/simpledateformat-not-parsing-time-correctly

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