SimpleDateFormat无法正确解析时间 [英] SimpleDateFormat not parsing time correctly

查看:84
本文介绍了SimpleDateFormat无法正确解析时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在一个(可能更多)日期时间发生的,其中时间部分在解析中是完全错误的.

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

代码:

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);
    }
}

输出:

文本2018-11-01T18:07:55.6725292Z解析为MDT Nov 11 20:00:00 MDT 2018

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.

推荐答案

这是Date,CalendarSimpleDateFormat类过时的问题之一.您不应该使用它,因为它已被Java 8中新的Date and Time API取代.它在java.time包中可用.

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);


似乎SimpleDateFormat最多只能读取三毫秒的数字.如果将日期的小数部分截断为三位数,即"2018-11-01T18:07:55.672"而不是"2018-11-01T18:07:55.6725292Z",则解析过程将起作用,并且还会更改相应的"S'模式说明符,即"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'".


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'".

这篇关于SimpleDateFormat无法正确解析时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆