Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse date-time with two or three milliseconds digits in java?

Here is my method to parse String into LocalDateTime.

    public static String formatDate(final String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");
        LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
        return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
    }

but this only works for input String like 2017-11-21 18:11:14.05 but fails for 2017-11-21 18:11:14.057 with DateTimeParseException.

How can I define a formatter that works for both .SS and .SSS?

like image 321
brain storm Avatar asked Jan 17 '18 00:01

brain storm


People also ask

How to parse Date time in Java?

DateTimeFormatter f = DateTimeFormat. forPattern("yyyy-MM-dd HH:mm:ss"); DateTime dateTime = f. parseDateTime("2012-01-10 23:13:26");

How to parse MM dd yyyy in Java?

Date deliverDate = new SimpleDateFormat("MM/dd/yy"). parse(deliverDateString); String dateString2 = new SimpleDateFormat("yyyy-MM-dd"). format(deliverDate);

How to format Date() in Java?

Java SimpleDateFormat Example String pattern = "MM-dd-yyyy"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); String date = simpleDateFormat. format(new Date()); System. out. println(date);


2 Answers

You would need to build a formatter with a specified fraction

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .appendPattern("yyyy-MM-dd HH:mm:ss")
  .appendFraction(ChronoField.MILLI_OF_SECOND, 2, 3, true) // min 2 max 3
  .toFormatter();

LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
like image 168
Sleiman Jneidi Avatar answered Sep 20 '22 00:09

Sleiman Jneidi


The answers by Basil Bourque and Sleiman Jneidi are excellent. I just wanted to point out that the answer by EMH333 has a point in it too: the following very simple modification of the code in the question solves your problem.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.[SSS][SS]");

The square bracket in the format pattern string enclose optional parts, so this accepts 3 or 2 decimals in the fraction of seconds.

  • Potential advantage over Basil Bourque’s answer: gives better input validation, will object if there is only 1 or there are four decimals on the seconds (whether this is an advantage depends entirely on your situation).
  • Advantage over Sleiman Jneidi’s answer: You don’t need the builder.

Possible downside: it accepts no decimals at all (as long as the decimal point is there).

As I said, the other solutions are very good too. Which one you prefer is mostly a matter of taste.

like image 38
Ole V.V. Avatar answered Sep 17 '22 00:09

Ole V.V.