【问题标题】:How to change Timestamp String to "DD.MM.YYYY"?如何将时间戳字符串更改为 \"DD.MM.YYYY\"?
【发布时间】:2022-11-04 23:05:04
【问题描述】:
我有不同格式的字符串需要转换为“DD.MM.YYYY”。
Thu, 3 Nov 2022 06:00:00 +0100 必须更改为 03.11.2022 和 01.11.2022 20:00:00 至 01.11.2022。所有格式都是字符串。我试着做
String pattern="DD.MM.YYYY";
DateTimeFormatter formatter=DateTimeFormatter.ofPattern(pattern);
new SimpleDateFormat(pattern).parse("01.11.2022 20:00:00")
我尝试过以下操作
java.time.LocalDateTime.parse(
item.getStartdatum(),
DateTimeFormatter.ofPattern( "DDMMYYYY" )
).format(
DateTimeFormatter.ofPattern("DD.MM.YYYY")
)
But got the error :::
Exception in thread "main" java.time.format.DateTimeParseException: Text 'Sun, 30 Oct 2022 00:30:00 +0200' could not be parsed at index 0
我也尝试过以下操作
String pattern="DD.MM.YYYY";
DateFormat format = new SimpleDateFormat(pattern);
Date date = format.parse(01.11.2022 20:00:00);
但是我没有得到正确的输出。
【问题讨论】:
标签:
java
string
date
datetime
【解决方案1】:
几件事……
- 如果您可以使用
java.time,请尽可能独占使用它(不要使用SimpleDateFormat 或类似的旧东西)
- 一个
DateTimeFormatter可以用来解析和格式Strings 表示日期时间,如果输入和输出格式不同,则需要两个不同的DateTimeFormatters
-
无法在索引 0 处解析文本“Sun,2022 年 10 月 30 日 00:30:00 +0200”由于您尝试使用模式
"DD.MM.YYYY" 解析它,这在几个层面上都是错误的:
- 该模式似乎期望
String 以数字表示月份的某天开始,但它以Thu 开头,这是一周中某天名称的缩写
- 符号
D 表示一年中的某一天,一个介于 1 和 366 之间的数字(在闰年,否则为 365)
- 符号
Y 表示基于周的年份
您可以改为执行以下操作:
public static void main(String[] args) {
// two example inputs
String first = "Thu, 3 Nov 2022 06:00:00 +0100";
String second = "01.11.2022 20:00:00";
// prepare a formatter for each pattern in order to parse the Strings
DateTimeFormatter dtfInFirst = DateTimeFormatter.ofPattern(
"EEE, d MMM uuuu HH:mm:ss x",
Locale.ENGLISH
);
// (second one does not have an offset from UTC, so the resulting class is different)
DateTimeFormatter dtfInSecond = DateTimeFormatter.ofPattern("dd.MM.uuuu HH:mm:ss");
// parse the Strings using the formatters
OffsetDateTime odt = OffsetDateTime.parse(first, dtfInFirst);
LocalDateTime ldt = LocalDateTime.parse(second, dtfInSecond);
// prepare a formatter, this time for output formatting
DateTimeFormatter dtfDateOnlySeparatedByDots = DateTimeFormatter.ofPattern("dd.MM.uuuu");
// extract the date part of each result of the parsing
LocalDate firstResult = odt.toLocalDate();
LocalDate secondResult = odt.toLocalDate();
// and print it formatted using the output formatter
System.out.println(first + " ---> "
+ firstResult.format(dtfDateOnlySeparatedByDots));
System.out.println(second + " ---> "
+ secondResult.format(dtfDateOnlySeparatedByDots));
}
它将输出转换结果如下:
Thu, 3 Nov 2022 06:00:00 +0100 ---> 03.11.2022
01.11.2022 20:00:00 ---> 03.11.2022