How to convert a long value like 2018051822111234L to yyyyMMdd HH:mm?
2018051822111234 -> 2018 05 18 22:11:12.
I tried with LocalDate.parse and DateFormatter(yyyy-MM-dd'T'HH:mm:ssZZZZZ). It doesn’t work for me.
How to convert a long value like 2018051822111234L to yyyyMMdd HH:mm?
2018051822111234 -> 2018 05 18 22:11:12.
I tried with LocalDate.parse and DateFormatter(yyyy-MM-dd'T'HH:mm:ssZZZZZ). It doesn’t work for me.
String asString = Long.toString(2018051822111234L);
asString = asString.substring(0, asString.length() - 2);
String result = LocalDateTime.parse(asString, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
.format(DateTimeFormatter.ofPattern("yyyy MM dd HH:mm:ss"));
Monsieur Nizet has already provided an excellent answer. It’s just me: I’d like to parse the full precision of the input long. It’s easier to throw away information later than it is to add it later if it wasn’t parsed at first.
Java 9 solution:
DateTimeFormatter longFormatter = DateTimeFormatter.ofPattern("uuuuMMddHHmmssSS");
DateTimeFormatter desiredFormatter = DateTimeFormatter.ofPattern("uuuu MM dd HH:mm:ss");
String asString = Long.toString(2018051822111234L);
String result = LocalDateTime.parse(asString, longFormatter)
.format(desiredFormatter);
This prints
2018 05 18 22:11:12
As you have already said yourself, this doesn’t work in Java 8 because of this bug in the JRE: DateTimeFormatter won't parse dates with custom format "yyyyMMddHHmmssSSS". The bug report mentions the following workaround:
DateTimeFormatter longFormatter = new DateTimeFormatterBuilder()
.appendPattern("uuuuMMddHHmmss")
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.toFormatter();
asString += '0';
The workaround formatter has three decimals on the seconds, corresponding to milliseconds, whereas your long has only two. So above I am appending an extra 0 to the string before parsing. It was what I could get to work in Java 8 (also tried appendFraction(), in vain). Now the result is the same as above.