0

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
DevJam
  • 19
  • 8

2 Answers2

1
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"));
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • So if i try to add the ms with the Pattern yyyyMMddHHmmssSSS and doesnt change the string length (String is ha a length of 17) it throws "cant parse at Index 0" – DevJam Jan 30 '18 at 13:50
  • This is an Bug and will fix in Java 9 -> https://bugs.openjdk.java.net/browse/JDK-8031085 – DevJam Jan 30 '18 at 14:35
  • The bug report you link to, @DevJam, mentions the following workaround: `DateTimeFormatter dtf = new DateTimeFormatterBuilder().appendPattern("yyyyMMddHHmmss").appendValue(ChronoField.MILLI_OF_SECOND, 3).toFormatter()`. I would prefer to try something similar to parse the full precision of your `long`. – Ole V.V. Jan 30 '18 at 15:32
1

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.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161