首页 > 解决方案 > 如何将此字符串“Mon Jan 01 00:00:00 AEDT 1990”转换为“1990101”?

问题描述

我有一个字符串“Mon Jan 01 00:00:00 AEDT 1990”,我需要将其转换为“yyyyMMdd”格式,因此在本例中为“19900101”。

我认为可以使用正则表达式来做到这一点,这样我就可以从字符串中提取年份、月份(但需要将 Jan 转换为 01 等)和日期,但我并不精通正则表达式。有人有想法么?

标签: javaregexstringdateparsing

解决方案


tl;博士

正则表达式是矫枉过正。

这是一个使用Java 内置的java.time类的单线解决方案。

ZonedDateTime                            // Represent a moment as seen through the wall-clock time used by the people of a certain region (a time zone).
.parse(                                  // Parse the input text.
    "Mon Jan 01 00:00:00 AEDT 1990" ,     
    DateTimeFormatter.ofPattern( 
        "EEE MMM dd HH:mm:ss z uuuu" ,   // Specify a custom formatting pattern to match our input.
        Locale.US                        // Specify a `Locale` for the human language to use in translating the name of month& day-of-week.
    )                                    // Returns a `DateTimeFormatter` object.
)                                        // Returns a `ZonedDateTime` object.
.toLocalDate()                           // Extract the date, without time-of-day and without time zone. 
.format(                                 // Generate text to represent the value of our `LocalDate` object.
    DateTimeFormatter.BASIC_ISO_DATE     // Use the predefined formatting pattern YYYYMMDD.
)                                        // Returns a String.

19900101

java.time

正则表达式对此太过分了。

现代方法使用java.time类。

指定自定义格式模式以适合您的输入。

指定语言环境以方便翻译星期几和月份的名称。

ZonedDateTime

解析为ZonedDateTime,从特定地区(时区)的人们使用的挂钟时间看到的时刻。

String input = "Mon Jan 01 00:00:00 AEDT 1990";
Locale locale = Locale.US;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , locale );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

System.out.println( "zdt: " + zdt );

zdt: 1990-01-01T00:00+11:00[澳大利亚/悉尼]

顺便说一句,您的输入字符串格式很糟糕。它使用了 2-4 个字符的伪时区,它们不是实际的时区,不是标准化的,也不是唯一的!另一个问题是取决于英语。而且很难解析。教育发布您的数据的人员了解ISO 8601标准的美妙之处,该标准是为将日期时间值交换为文本而创建的。

LocalDate

你只想要日期。所以提取一个LocalDate.

LocalDate ld = zdt.toLocalDate() ;  // Extract only the date, leaving behind the time-of-day and the time zone.

您所需的输出格式已在DateTimeFormatter类中定义。日期的标准ISO 8601格式是 YYYY-MM-DD。它的一种变体被称为“基本”,这意味着它最大限度地减少了分隔符的使用:YYYYMMDD。

String output = ld.format( DateTimeFormatter.BASIC_ISO_DATE ) ;

19900101


推荐阅读