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

前端 未结 10 1697
迷失自我
迷失自我 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:07

    Since you're using it on the mobile device, the first method is preferable. The reason is that your code should be independent of specific calendar, DST and other problems, such as seconds overrun(leap seconds).

    You have to remove dependence on GregorianCalendar and create it using Calendar.getInstance().

    0 讨论(0)
  • 2021-01-07 18:11

    The two methods will behave differently on daylight savings boundaries. The first method will continue returning the same time of the day, regardless of daylight savings status. The second method will return times which vary an hour in each direction as daylight savings time starts and stops.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-07 18:14

    The first will be slower, so if performance is an issue, the second one is better.

    0 讨论(0)
提交回复
热议问题