Get first next Monday after certain date?

前端 未结 5 671
自闭症患者
自闭症患者 2020-12-01 20:56

I know there is the same question here, but I have tried the answer provided and it returned an output that I don\'t understand. I am confused by the answer and I don\'t thi

5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 21:46

    tl;dr

    LocalDate.of( 2014 , Month.JUNE , 12 )                    // Represent a date-only value, without time-of-day and without time zone.
             .with(                                           // Move from one date to another by passing an implementation of the `TemporalAdjuster` interface. 
                 TemporalAdjusters.next( DayOfWeek.MONDAY )   // Use an existing implementation found on utility class `TemporalAdjusters` (plural versus singular).
             )                                                // Returns another fresh `LocalDate` object rather than altering the original, per immutable objects design.
    

    Using java.time

    You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

    The LocalDate class represents a date-only value without time-of-day and without time zone.

    LocalDate ld = LocalDate.of( 2014 , Month.JUNE , 12 ) ;
    

    To get the following Monday, use a TemporalAdjuster implementation found in TemporalAdjusters class.

    LocalDate nextMonday = ld.with( TemporalAdjusters.next( DayOfWeek.MONDAY ) ) ;
    

    If you want to go with the original date if it is itself a Monday, then use nextOrSame adjuster.

    LocalDate nextOrSameMonday = ld.with( TemporalAdjusters.nextOrSame( DayOfWeek.MONDAY ) ) ;
    

    About java.time

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

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

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

    Where to obtain the java.time classes?

    • Java SE 8, Java SE 9, and later
      • Built-in.
      • Part of the standard Java API with a bundled implementation.
      • Java 9 adds some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
      • See How to use ThreeTenABP….

    The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

提交回复
热议问题