Add 1 Week to a Date, which way is preferred?

前端 未结 10 1745
迷失自我
迷失自我 2021-01-07 17:30

I am reviewing some code at work and came across an inconsistency in how the code handles adding 1 week to the current time and was wondering if there was any reason why one

10条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 18:11

    For a date-only value, see the Answer by javaHelper. The LocalDate class purposely has no time-of-day and no time zone.

    ZonedDateTime

    For a date-time value, use ZonedDateTime to represent a date and a time-of-day along with a time zone to account for anomalies such as Daylight Saving Time (DST).

    ZoneId zoneId = ZoneId.of( "America/Montreal" );
    ZonedDateTime now = ZonedDateTime.now( zoneId );
    ZonedDateTime weekLater = now.plusWeeks( 1 );
    

    Or add some arbitrary number of days.

    ZonedDateTime later = now.plusDays( someNumberOfDays );
    

    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.

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

提交回复
热议问题