DateTimeFormatter Accepting Multiple Dates and Converting to One (java.time library)

前端 未结 4 1210
情话喂你
情话喂你 2020-12-09 06:26

I am trying to write a DateTimeFormatter that will allow me to take in multiple different String formats, and then convert the String

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-09 06:56

    The Answer by Andreas is correct and should be accepted.

    Check length of string

    As an alternative, you can simply test the length of your string and apply one of two formatters.

    DateTimeFormatter fDateOnly = DateTimeFormatter.ofPattern( "MM/dd/uuuu" ) ;
    DateTimeFormatter fDateTime = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
    
    LocalDate ld = null ;
    if( input.length() == 10 ) {
        try {
            ld = LocalDate.parse( input , fDateOnly ) ;
        } catch (DateTimeParseException  e ) {
            …
        }
    } else if ( input.length() == 19 ) {
        try {
            LocalDateTime ldt = LocalDateTime.parse( input , fDateTime ) ;
            ld = ldt.toLocalDate() ;
        } catch (DateTimeParseException  e ) {
            …
        }
    } else {
        // Received unexpected input.
        …
    }
    
    String output = ld.format( fDateOnly ) ;
    

    Be aware that you can let java.time automatically localize when generating a string representing the value of your date-time rather than hard-code a specific format. See DateTimeFormatter.ofLocalizedDate.

提交回复
热议问题