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…

JavaScript

Which prints out …

JavaScript

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

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

JavaScript

Which prints out …

JavaScript

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