日期时间解析错误 [英] Datetime parsing error

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

问题描述

我在Java中解析日期时遇到问题。下面是代码。

I am having problem parsing dates in Java. Below is the code.

 String dateString = "2017-12-13T16:49:20.730555904Z";
 List<String> formatStrings = Arrays.asList("yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'");

    for (String formatString : formatStrings)
    {
        try
        {
            SimpleDateFormat formatter = new SimpleDateFormat(formatString);
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date d = formatter.parse(dateString);
            System.out.println("Format is:" + formatString);
            System.out.println("Orignal Date: " + d);
            System.out.println("Orignal MS: " + d.getTime());

            return d;
        }
        catch (ParseException e) {}
    }

    return null;
}

当我运行这个程序时,我得到以下输出。

When I run this program, I get the following output.

Format is:yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'
Orignal Date: Fri Dec 22 03:45:15 UTC 2017
Orignal MS: 1513914315904

我不知道为什么当它应该 12月13日时,它给了我 12月22日。但是,如果我将输入日期更改为此。

I am not sure why it is giving me Dec 22 when it should be Dec 13. But if I change my input date to this.

String dateString = "2017-12-13T16:49:20.7Z";

即在Z之前只有一个字符。然后我得到正确的输出。

i.e only one character before the Z. then I get the correct output.

Format is:yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSS'Z'
Orignal Date: Wed Dec 13 16:49:20 UTC 2017
Orignal MS: 1513183760007

它给我正确的输出直到3在Z之前的数字。如果超过3个数字比我输出错误。

It gives me correct output till 3 numbers before the Z. If more than 3 numbers than I got the wrong output.

如果有人可以指出我在这里缺少的东西,那就太棒了。

It would be great if someone can point me out what I am missing here.

PS:我在android中解析这些日期。我已将min API级别设置为16,并且对于低于26的API级别,java.time不可用。

推荐答案

S in SimpleDateFormat 指定毫秒数,而不是几分之一秒。您已指定730555904毫秒,即约8.45天 - 因此日期更改。

S in SimpleDateFormat specifies a number of milliseconds, not a fraction of a second. You've specified 730555904 milliseconds, which is ~8.45 days - hence the date change.

java.util.Date 只有毫秒精度。我建议使用 java.time 包,它的精度为纳秒,就像输入一样。使用 DateTimeFormatter 进行解析。请注意,在 DateTimeFormatter 中, S 说明符的秒数分数。

java.util.Date only has a precision of milliseconds. I would recommend using the java.time package, which has a precision of nanoseconds, like your input. Use DateTimeFormatter for parsing. Note that in DateTimeFormatter, the S specifier is for fraction-of-a-second.

更好的是, Instant.parse 无论如何都使用正确的格式:

Even better, Instant.parse uses the right format anyway:

import java.time.*;

public class Test {
    public static void main(String... args) throws Exception {
        String text = "2017-12-13T16:49:20.730555904Z";
        Instant instant = Instant.parse(text);
        System.out.println(instant);
    }
}

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

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