原文:
I know this is really a beginner question, but it seems I can't find any good solution for this.
So I have a String that I get from a JSON database website that is:
DateTime = "\/Date(1598036400000)\/"
But the question is how do I convert this String to a real DateTime?
# Answer 1
You will have to perform several steps due to the value not being a long in its original representation "/Date(1598036400000)/". The numeric value inside that String is representing a moment in time in epoch milliseconds and you have to remove the remaining characters or substrings. Here's an example...
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);
}
... which outputs
2020-08-21T21:00+02:00[CET]
If you need a differently formatted String, you can use a DateTimeFormatter that even considers different locales or languages.
The output of
System.out.println(zdt.format(
DateTimeFormatter.ofPattern("EEEE, dd. MMMM yyyy HH:mm:ss", Locale.GERMAN))
);
is
Freitag, 21. August 2020 21:00:00