How to check if it's Saturday/Sunday?

前端 未结 2 1086
耶瑟儿~
耶瑟儿~ 2020-12-06 09:14

What this code does is print the dates of the current week from Monday to Friday. It works fine, but I want to ask something else: If today is Saturday or Sunday I want it t

2条回答
  •  自闭症患者
    2020-12-06 09:36

    tl;dr

    Core code concept:

    EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY )           // Instantiate a n implementation of `Set` highly optimized in both memory usage and execution speed for collecting enum objects. 
           .contains(                                             // Ask if our target `DayOfWeek` enum object is in our `Set`. 
                LocalDate.now( ZoneId.of( "America/Montreal" ) )  // Determine today’s date as seen by the people of a particular region (time zone).
                         .getDayOfWeek()                          // Determine the `DayOfWeek` enum constant representing the day-of-week of this date.
            )
    

    java.time

    The modern way is with the java.time classes.

    The DayOfWeek enum provides seven objects, for Monday-Sunday.

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

    A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

    ZoneId z = ZoneId.of( "America/Montreal" );
    LocalDate today = LocalDate.now( z );
    DayOfWeek dow = today.getDayOfWeek();
    

    Define the weekend as a set of DayOfWeek objects. Note that EnumSet is an especially fast and low-memory implementation of Set designed to hold Enum objects such as DayOfWeek.

    Set weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY );
    

    Now we can test if today is a weekday or a weekend.

    Boolean todayIsWeekend = weekend.contains( dow );
    

    The Question said we want to jump to the start of next week if this is a weekend. To do that, use a TemporalAdjuster which provides for classes that can manipulate date-time objects. In java.time we have immutable objects. This means we produce new instances based on the values within an existing object rather than alter ("mutate") the original. The TemporalAdjusters class (note the plural 's') provides several handy implementations of TemporalAdjuster including next( DayOfWeek ).

    DayOfWeek firstDayOfWeek = DayOfWeek.MONDAY ;
    LocalDate startOfWeek = null ;
    if( todayIsWeekend ) {
        startOfWeek = today.with( TemporalAdjusters.next( firstDayOfWeek ) );
    } else {
        startOfWeek = today.with( TemporalAdjusters.previousOrSame( firstDayOfWeek ) );
    }
    

    We soft-code the length of the week in case our definition of weekend ever changes.

    LocalDate ld = startOfWeek ;
    int countDaysToPrint = ( DayOfWeek.values().length - weekend.size() );
    for( int i = 1 ; i <= countDaysToPrint ; i++ ) {
        System.out.println( ld );
        // Set up the next loop.
        ld = ld.plusDays( 1 );
    }
    

    See live code in IdeOne.com.


    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 java.time.

    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 and 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 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….

    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.

提交回复
热议问题