简体   繁体   English

将字符串转换或格式化为日期

[英]Convert or format string to date

I am struggling with this .. I have an input string - like this: 2021-10-13 11:33:16.000-04我正在为此苦苦挣扎..我有一个输入字符串 - 像这样:2021-10-13 11:33:16.000-04

Using Java.使用 Java。

I need to get a Date object from it.我需要从中获取一个 Date 对象。 which formatting pattern can I use ?我可以使用哪种格式模式?

I try with these我试着用这些

SimpleDateFormat inFormatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSS'-'ZZ");

and

SimpleDateFormat inFormatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss.SSSZZ");

and I keep getting我不断得到

java.text.ParseException: Unparseable date: "2021-10-13 11:33:16.000-04"
  at java.base/java.text.DateFormat.parse(DateFormat.java:396)
  at com.dima.tests.DatesConversions.main(DatesConversions.java:24)

Please, help !!请帮忙 !!

Don't use Date as it is outdated.不要使用 Date,因为它已经过时了。 Use the classes in the java.time使用java.time 中的类

OffsetDateTime odt = OffsetDateTime.parse(str, 
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSX"));       
System.out.println(odt);

Prints印刷

2021-10-13T11:33:16-04:00

java.time时间

Even though you need to give an old-fashionede Date object to a legacy API beyond your control, I still recommend that you use java.time, the modern Java date and time API, in your own code.即使您需要将老式Date对象提供给您无法控制的遗留 API,我仍然建议您在自己的代码中使用 java.time,现代 Java 日期和时间 API。 The final conversion to Date is pretty straight-forward.Date的最终转换非常简单。

I'd use this formatter for maximum reuse of existing formatters:我会使用这个格式化程序来最大限度地重用现有的格式化程序:

private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ISO_LOCAL_DATE)
        .appendLiteral(' ')
        .append(DateTimeFormatter.ISO_LOCAL_TIME)
        .appendOffset("+HHmm", "+00")
        .toFormatter(Locale.ROOT);

Then we parse and convert like this:然后我们像这样解析和转换:

    String input = "2021-10-13 11:33:16.000-04";
    OffsetDateTime dateTime = OffsetDateTime.parse(input, PARSER);
    System.out.println(dateTime);
    
    Instant i = dateTime.toInstant();
    Date oldfashionedDate = Date.from(i);
    System.out.println(oldfashionedDate);

Output in my time zone, Europe/Copenhagen:输出在我的时区,欧洲/哥本哈根:

 2021-10-13T11:33:16-04:00 Wed Oct 13 17:33:16 CEST 2021

Denmark is at offset +02:00 at this time of year, so 6 hours ahead of the UTC offset -04 from your string.丹麦在一年中的这个时候偏移 +02:00,因此比您的字符串的 UTC 偏移 -04 提前 6 小时。 Therefore Date.toString() confusingly prints a clock hour that is 6 hours ahead of the original time of day.因此Date.toString()令人困惑地打印比一天中的原始时间提前 6 小时的时钟小时。

Note: if your forward service accepts anything else than an old-fashioned Date , you should not be using that class.注意:如果您的转发服务接受老式Date以外的任何内容,则不应使用该类。 For example, if a String is required, the OffsetDateTime that we got can be formatted into a new string using a second DateTimeFormatter (or in lucky cases, its toString method).例如,如果需要一个String ,我们得到的OffsetDateTime可以使用第二个DateTimeFormatter (或者在幸运的情况下,它的toString方法)格式化为一个新字符串。

What went wrong in your code?你的代码出了什么问题?

First, a UTC offset can have positive or negative sign.首先,UTC 偏移量可以有正号或负号。 Instead of -04 you could have had for example +09 .例如,您可以使用+09而不是-04 Formatters are designed for to take the sign, + or - , as part of the offset.格式化程序旨在将符号+-作为偏移量的一部分。 Therefore hardcoding the minus sign as a literal, as in your first attempt, is bound to fail.因此,在您的第一次尝试中,将减号硬编码为文字肯定会失败。 In your second attempt, yyyy-MM-dd HH:mm:ss.SSSZZ , you are already closer.在您的第二次尝试中, yyyy-MM-dd HH:mm:ss.SSSZZ ,您已经接近了。 However, ZZ is for an offset with sign and four digits (like +0530 or -0400 ; hour and minute), so does not work for a two-digit offset like -04 .然而, ZZ为带符号和四个数字(如一个偏移+0530-0400 ;小时和分钟),所以不工作两位数像偏移-04 Your SimpleDateFormat expected more digits where your string ended and therefore threw the exception that you saw.您的SimpleDateFormat期望您的字符串结尾处有更多数字,因此抛出了您看到的异常。

Link关联

Oracle tutorial: Date Time explaining how to use java.time. Oracle 教程:解释如何使用 java.time 的日期时间

Since you are using ISO 8601 time zone timezone, you have the use the below pattern.由于您使用的是ISO 8601 time zone时区,因此您可以使用以下模式。

SimpleDateFormat inFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSX");

And then, to get the date:然后,要获取日期:

Date date = inFormatter.parse("2021-10-13 11:33:16.000-04");

Always check the documentation .始终检查文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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