Java - Date format for Multiple Scenarios

后端 未结 2 1645
一整个雨季
一整个雨季 2021-01-29 10:06

I have a java component to format the date that I retrieve. Here is my code:

    Format formatter      = new SimpleDateFormat(\"yyyyMMdd\");
        String s = \         


        
2条回答
  •  无人及你
    2021-01-29 10:55

    Different types

    String s = "2019-04-23 06:57:00";

    String s = "2019-04-23";

    These are two different kinds of information. One is a date with time-of-day, the other is simply a date. So you should be parsing each as different types of objects.

    LocalDateTime.parse

    To comply with the ISO 8601 standard format used by default in the LocalDateTime class, replace the SPACE in the middle with a T. I suggest you educate the publisher of your data about using only ISO 8601 formats when exchanging date-time values as text.

    LocalDateTime ldt1 = LocalDateTime.parse( "2019-04-23 06:57:00".replace( " " , "T" ) ) ;
    

    The fractional second parses by default as well.

    LocalDateTime ldt2 = LocalDateTime.parse( "2019-04-23 06:57:00.0".replace( " " , "T" ) ) ;
    

    See this code run live at IdeOne.com.

    ldt1.toString(): 2019-04-23T06:57

    ldt2.toString(): 2019-04-23T06:57

    LocalDate.parse

    Your date-only input already complies with ISO 8601.

    LocalDate ld = LocalDate.parse( "2019-04-23" ) ;
    

    See this code run live at IdeOne.com.

    ld.toString(): 2019-04-23

    Date with time-of-day

    You can strip out the time-of-day from the date.

    LocalDate ld = ldt.toLocalDate() ;
    

    And you can add it back in.

    LocalTime lt = LocalTime.parse( "06:57:00" ) ;
    LocalDateTime ldt = ld.with( lt ) ;
    

    Moment

    However, be aware that a LocalDateTime does not represent a moment, is not a point on the timeline. Lacking the context of a time zone or offset-from-UTC, a LocalDateTime cannot hold a moment, as explained in its class JavaDoc.

    For a moment, use the ZonedDateTime, OffsetDateTime, or Instant classes. Teach the publisher of your data to include the offset, preferably in UTC.

    Avoid legacy date-time classes

    The old classes SimpleDateFormat, Date, and Calendar are terrible, riddled with poor design choices, written by people not skilled in date-time handling. These were supplanted years ago by the modern java.time classes defined in JSR 310.

提交回复
热议问题