Inconsistent date parsing using SimpleDateFormat

后端 未结 4 1122
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 20:14

I\'m really scratching my head on this one. I\'ve been using SimpleDateFormats with no troubles for a while, but now, using a SimpleDateFormat to parse dates is

4条回答
  •  抹茶落季
    2020-12-17 21:03

    tl;dr

    LocalDateTime ldt = LocalDateTime.parse( "2009-08-19 12:00:00".replace( " " , "T" ) );
    

    java.time

    Other Answers are correct but use legacy date-time classes. Those troublesome old classes have been supplanted by the java.time classes.

    Your input string is close to standard ISO 8601 format. Tweak by replacing the SPACE in the middle with a T. Then it can be parsed without specifying a formatting pattern. The java.time classes use ISO 8601 by default when parsing/generating Strings.

    String input = "2009-08-19 12:00:00".replace( " " , "T" );
    

    The input data has no info about offset-from-UTC or time zone. So we parse as a LocalDateTime.

    LocalDateTime ldt = LocalDateTime.parse( input );
    

    If by the context you know the intended offset, apply it. Perhaps it was intended for UTC (an offset of zero), where we can use the constant ZoneOffset.UTC.

    OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC );
    

    Or perhaps you know it was intended for a particular time zone. A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

    ZonedDateTime zdt = ldt.atZone( ZoneId.of( "America/Montreal" ) );
    

    About java.time

    The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

    The Joda-Time project, now in maintenance mode, advises migration to java.time.

    To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

    Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

提交回复
热议问题