如何在Java中将字符串转换为日期和时间

问题描述

我知道这确实是一个初学者的问题,但是看来我找不到任何好的解决方案。

所以我有一个String,它是从JSON数据库网站获得的:

DateTime = "\/Date(1598036400000)\/" 

但是问题是如何将String转换为真实的DateTime?

解决方法

由于该值不是其原始表示形式long中的"/Date(1598036400000)/",因此您必须执行几个步骤。 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