How to analyze date-time with two or three millisecond digits in java?

Here is my method for parsing a string in 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 as 2017-11-21 18:11:14.05 but does not execute for 2017-11-21 18:11:14.057 s DateTimeParseException.

How can I identify a formatter that works for .SSboth and .SSS?

+4
source share
4 answers

TL; DR

No need to define a formatter at all.

LocalDateTime.parse(
    "2017-11-21 18:11:14.05".replace( " " , "T" )
)

ISO 8601

Sleiman Jneidi's answer is especially smart and high-tech, but there is an easier way.

ISO 8601, , java.time. . ( ) () .

. SPACE T.

String input = "2017-11-21 18:11:14.05".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );

ldt.toString(): 2017-11-21T18: 11:14.050

+2

DateTimeFormatterformatter 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);
+8

Basil Bourque . , EMH333 : .

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

, 3 2 .

  • Basil Bourques : , , 1 ( , ).
  • Sleiman Jneidis: .

: ( ).

, . , .

+2

Using Java 8, you can use a DateTimeFormatterBuildertemplate as well. See this answer for more information.

public static String formatDate(final String date) {

  DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd HH:mm:ss.SSS]" 
         + "[yyyy-MM-dd HH:mm:ss.SS]"));

  DateTimeFormatter formatter = dateTimeFormatterBuilder.toFormatter();

  try {
    LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
    return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
  } catch (DateTimeParseException e) {
    return "";
  }
}
+1
source

Source: https://habr.com/ru/post/1692283/


All Articles