Skip to content
Advertisement

Java convert DateTime from “yyyy-MM-dd HH:mm:ss.SSSSSSS” to “yyyy-MM-dd HH:mm:ss.S” or from “yyyy-MM-dd HH:mm:ss.SSSSSSS” to “yyyy-MM-dd HH:mm:ss.SSS”

Java 11

I want to convert the date in “yyyy-MM-dd HH:mm:ss.SSSSSSS” to either “yyyy-MM-dd HH:mm:ss.S” or “yyyy-MM-dd HH:mm:ss.SSS” based on milliseconds value. If milliseconds are all zeros, then I just want single zero but if it is non-zero value then I want just value omitting trailing zeros.

Example :

  1. Input : 2021-03-10 16:37:02.4230000 => Desired Output : 2021-03-10 16:37:02.423
  2. Input : 2021-03-10 16:39:51.0000000 => Desired output : 2021-03-10 16:39:51.0
  3. Input : 2021-04-22 23:03:52.0234000 => Desired output : 2021-04-22 23:03:52.0234

Advertisement

Answer

So, I started out with something like…

String text = "2021-03-10 16:37:02.4230000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS");

LocalDateTime ldt1 = LocalDateTime.parse("2021-03-10 16:37:02.4230000", formatter);
DateTimeFormatter shortFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S");
System.out.println(shortFormatter.format(ldt1));

LocalDateTime ldt2 = LocalDateTime.parse("2021-03-10 16:39:51.0000000", formatter);
System.out.println(shortFormatter.format(ldt2));

Which prints out …

2021-03-10 16:37:02.4
2021-03-10 16:39:51.0

Hmmm 🤔, not quite what we’re looking for.

Lucky for us, there’s the DateTimeFormatterBuilder class. So next, I tried something like…

DateTimeFormatter toFormatter = new DateTimeFormatterBuilder()
        .appendPattern("yyyy-MM-dd HH:mm:ss")
        .appendFraction(ChronoField.MILLI_OF_SECOND, 1, 9, true)
        .toFormatter();

System.out.println(toFormatter.format(ldt1));
System.out.println(toFormatter.format(ldt2));

Which prints out …

2021-03-10 16:37:02.423
2021-03-10 16:39:51.0

Success 🎉

Now, please note, I’ve not really used DateTimeFormatterBuilder before, so there might be some other, really super awesome cool way to achieve the same or better result, but hay, it’s a nice start

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement