如何将时间戳字符串更改为“DD.MM.YYYY”?

Jee*_*eet 2 java string datetime date

我需要不同格式的字符串来转换为“DD.MM.YYYY”。

"Thu, 3 Nov 2022 06:00:00 +0100"必须改为"03.11.2022"

"01.11.2022 20:00:00""01.11.2022"

所有格式均为String.

我尝试做

String pattern="DD.MM.YYYY";
DateTimeFormatter formatter=DateTimeFormatter.ofPattern(pattern);

new SimpleDateFormat(pattern).parse("01.11.2022 20:00:00")
Run Code Online (Sandbox Code Playgroud)

我也尝试过执行以下操作

java.time.LocalDateTime.parse(
        item.getStartdatum(),
        DateTimeFormatter.ofPattern( "DDMMYYYY" )
    ).format(
        DateTimeFormatter.ofPattern("DD.MM.YYYY")
    )
Run Code Online (Sandbox Code Playgroud)

但出现错误:

Exception in thread "main" java.time.format.DateTimeParseException:
Text 'Sun, 30 Oct 2022 00:30:00 +0200' could not be parsed at index 0
Run Code Online (Sandbox Code Playgroud)

我也尝试执行以下操作

Exception in thread "main" java.time.format.DateTimeParseException:
Text 'Sun, 30 Oct 2022 00:30:00 +0200' could not be parsed at index 0
Run Code Online (Sandbox Code Playgroud)

但是,我没有得到正确的输出。我怎样才能得到我想要的结果?

deH*_*aar 5

几件事\xe2\x80\xa6

\n
    \n
  • 如果可以使用java.time,请在可能的情况下专门使用它(没有SimpleDateFormat或类似的遗留内容)
  • \n
  • aDateTimeFormatter可用于解析格式化String表示日期时间的 s,如果输入和输出格式不同,则需要两个不同的DateTimeFormatters
  • \n
  • 由于您尝试使用模式解析文本“Sun, 30 Oct 2022 00:30:00 +0200\”,因此无法在索引 0 处进行解析"DD.MM.YYYY",这在多个级别上都是错误的:\n
      \n
    • 该模式似乎期望以String月份中某一天的数字表示形式开头,但它以Thu一周中某一天名称的缩写形式开头
    • \n
    • 该符号D表示一年中的第几天,是 1 到 366 之间的数字(闰年为 365)
    • \n
    • 该符号Y表示基于周的年份
    • \n
    \n
  • \n
\n

在 JavaDocs 中阅读有关这些符号的更多信息DateTimeFormatter

\n

您可以执行以下操作:

\n
public static void main(String[] args) {\n    // two example inputs\n    String first = "Thu, 3 Nov 2022 06:00:00 +0100";\n    String second = "01.11.2022 20:00:00";\n    // prepare a formatter for each pattern in order to parse the Strings\n    DateTimeFormatter dtfInFirst = DateTimeFormatter.ofPattern(\n                                        "EEE, d MMM uuuu HH:mm:ss x",\n                                        Locale.ENGLISH\n                                   );\n    // (second one does not have an offset from UTC, so the resulting class is different)\n    DateTimeFormatter dtfInSecond = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss");\n    // parse the Strings using the formatters\n    OffsetDateTime odt = OffsetDateTime.parse(first, dtfInFirst);\n    LocalDateTime ldt = LocalDateTime.parse(second, dtfInSecond);\n    // prepare a formatter, this time for output formatting\n    DateTimeFormatter dtfDateOnlySeparatedByDots = DateTimeFormatter.ofPattern("dd.MM.uuuu");\n    // extract the date part of each result of the parsing\n    LocalDate firstResult = odt.toLocalDate();\n    LocalDate secondResult = ldt.toLocalDate();\n    // and print it formatted using the output formatter\n    System.out.println(first + " ---> "\n                             + firstResult.format(dtfDateOnlySeparatedByDots));\n    System.out.println(second + " ---> " \n                              + secondResult.format(dtfDateOnlySeparatedByDots));\n}\n
Run Code Online (Sandbox Code Playgroud)\n

将会输出转换结果如下:

\n
Thu, 3 Nov 2022 06:00:00 +0100 ---> 03.11.2022\n01.11.2022 20:00:00 ---> 01.11.2022\n
Run Code Online (Sandbox Code Playgroud)\n

Locale由于名称的存在(星期几和月份),第一个格式化程序将需要 a 。您无法使用任何专门的数字解析器来解析它,并且语言/文化必须匹配。<

\n
\n

简洁版本

\n
public static void main(String[] args) {\n    // two example inputs\n    String first = "Thu, 3 Nov 2022 06:00:00 +0100";\n    String second = "01.11.2022 20:00:00";\n    // prepare a custom formatter for the second pattern\n    DateTimeFormatter dtfInSecond = DateTimeFormatter\n                                        .ofPattern("dd.MM.uuuu HH:mm:ss");\n    // parse the first String by means of a built-in RFC formatter\n    OffsetDateTime odt = OffsetDateTime.parse(\n                                first,\n                                DateTimeFormatter.RFC_1123_DATE_TIME);\n    // parse the second String using the custom formatter\n    LocalDateTime ldt = LocalDateTime.parse(second, dtfInSecond);\n    // prepare a formatter, this time for output formatting\n    DateTimeFormatter dtfDateOnlySeparatedByDots = DateTimeFormatter\n                                                        .ofPattern("dd.MM.uuuu");\n    // and print it formatted using the output formatter\n    System.out.println(first + " ---> "\n                             + odt.format(dtfDateOnlySeparatedByDots));\n    System.out.println(second + " ---> " \n                              + ldt.format(dtfDateOnlySeparatedByDots));\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

暗示:

\n

对于像您评论中提到的日期\xe2\x80\xa6

\n
Text \'9.28.2022 6:30:00\' could not be parsed at index 0\n
Run Code Online (Sandbox Code Playgroud)\n

您将必须使用具有单位数的月份中的日期和一天中的小时的模式,如果9.8.2022可能的话,甚至可能是一年中的月份。但是,您肯定需要切换月份和月份,因为没有月份号。一年28。

\n

简短的例子:

\n
Text \'9.28.2022 6:30:00\' could not be parsed at index 0\n
Run Code Online (Sandbox Code Playgroud)\n

执行于main,这将输出

\n
String third = "9.28.2022 6:30:00";\nDateTimeFormatter dtfInThird = DateTimeFormatter\n                                    .ofPattern("M.d.uuuu H:mm:ss");\nLocalDateTime ldtThird = LocalDateTime.parse(third, dtfInThird);\nSystem.out.println(third + " ---> " \n                         + ldtThird.format(dtfDateOnlySeparatedByDots));\n
Run Code Online (Sandbox Code Playgroud)\n


Arv*_*ash 5

java.util日期时间 API 及其格式化 APISimpleDateFormat过时且容易出错。建议完全停止使用它们并切换到现代日期时间 API

deHaar 已经写了一个很好的答案。但是,如果您想使用单个DateTimeFormatter,您可以检查此答案。

为了进行解析,您可以DateTimeFormatter使用可选模式和默认时区偏移值构建一个(因为第二个日期时间字符串中没有时区偏移),如下所示:

DateTimeFormatter parser = new DateTimeFormatterBuilder()
    .appendPattern("[d.M.uuuu H:m:s][EEE, d MMM uuuu H:m:s X]")
    .parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
    .toFormatter(Locale.ENGLISH);
Run Code Online (Sandbox Code Playgroud)

其中可选模式位于方括号中。或者,您可以使用DateTimeFormatterBuilder#optionalStartDateTimeFormatterBuilder#optionalEnd来指定可选模式。

OffsetDateTime使用此解析器,您可以使用以下命令解析给定的日期时间字符串并将其格式化为所需的字符串DateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu", Locale.ENGLISH);
Run Code Online (Sandbox Code Playgroud)

演示

public class Main {
  public static void main(String[] args) {
    DateTimeFormatter parser = new DateTimeFormatterBuilder()
        .appendPattern("[d.M.uuuu H:m:s][EEE, d MMM uuuu H:m:s X]")
        .parseDefaulting(ChronoField.OFFSET_SECONDS, 0)
        .toFormatter(Locale.ENGLISH);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.uuuu", Locale.ENGLISH);

    // Test
    Stream.of(
          "Thu, 3 Nov 2022 06:00:00 +0100",
          "01.11.2022 20:00:00"
        )
        .map(s -> OffsetDateTime.parse(s, parser).format(formatter).toString())
        .forEach(System.out::println);
    ;
  }
}
Run Code Online (Sandbox Code Playgroud)

输出

03.11.2022
01.11.2022
Run Code Online (Sandbox Code Playgroud)

笔记

  1. 请务必检查DateTimeFormatter文档以了解Yand之间的区别以及andy之间的区别。Dd
  2. 你可以用yof 代替u,但我更喜欢用 u代替y DateTimeFormatter
  3. 从Trail: Date Time中了解有关现代日期时间 API 的更多信息。