如何在 Java 中将字符串转换为日期和时间
how to convert String to Date and Time in Java
我知道这确实是一个新手问题,但我似乎找不到任何好的解决方案。
所以我有一个 String
,我从 JSON 数据库网站获得的是:
DateTime = "\/Date(1598036400000)\/"
但问题是如何将此 String
转换为真正的 DateTime?
由于值在其原始表示 "/Date(1598036400000)/"
中不是 long
,因此您将不得不执行几个步骤。 String
中的数值表示以纪元毫秒为单位的时刻,您必须删除剩余的字符或子字符串。这是一个例子...
public static void main(String[] args) {
// take the original String value,
String datetime = "/Date(1598036400000)/";
// remove anything that isn't a digit,
String millisStr = datetime.replace("/", "").replace("Date(", "").replace(")", "");
// then convert it to a long,
long millis = Long.valueOf(millisStr);
// and create a moment in time (Instant) from the long
Instant instant = Instant.ofEpochMilli(millis);
// and finally use the moment in time to express that moment in a specific time zone
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("CET"));
// and print its default String representation
System.out.println(zdt);
}
...输出
2020-08-21T21:00+02:00[CET]
如果您需要不同格式的 String
,您可以使用甚至考虑不同区域设置或语言的 DateTimeFormatter
。
的输出
System.out.println(zdt.format(
DateTimeFormatter.ofPattern("EEEE, dd. MMMM yyyy HH:mm:ss", Locale.GERMAN))
);
是
Freitag, 21. August 2020 21:00:00
我知道这确实是一个新手问题,但我似乎找不到任何好的解决方案。
所以我有一个 String
,我从 JSON 数据库网站获得的是:
DateTime = "\/Date(1598036400000)\/"
但问题是如何将此 String
转换为真正的 DateTime?
由于值在其原始表示 "/Date(1598036400000)/"
中不是 long
,因此您将不得不执行几个步骤。 String
中的数值表示以纪元毫秒为单位的时刻,您必须删除剩余的字符或子字符串。这是一个例子...
public static void main(String[] args) {
// take the original String value,
String datetime = "/Date(1598036400000)/";
// remove anything that isn't a digit,
String millisStr = datetime.replace("/", "").replace("Date(", "").replace(")", "");
// then convert it to a long,
long millis = Long.valueOf(millisStr);
// and create a moment in time (Instant) from the long
Instant instant = Instant.ofEpochMilli(millis);
// and finally use the moment in time to express that moment in a specific time zone
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.of("CET"));
// and print its default String representation
System.out.println(zdt);
}
...输出
2020-08-21T21:00+02:00[CET]
如果您需要不同格式的 String
,您可以使用甚至考虑不同区域设置或语言的 DateTimeFormatter
。
System.out.println(zdt.format(
DateTimeFormatter.ofPattern("EEEE, dd. MMMM yyyy HH:mm:ss", Locale.GERMAN))
);
是
Freitag, 21. August 2020 21:00:00