开发者

How to check if it's Saturday/Sunday?

What this code does is print the dates of the current week from Monday to Friday. It works fine, but I want to ask s开发者_运维百科omething else: If today is Saturday or Sunday I want it to show the next week. How do I do that?

Here's my working code so far (thanks to StackOverflow!!):

// Get calendar set to current date and time
Calendar c = Calendar.getInstance();

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

// Print dates of the current week starting on Monday to Friday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i <= 4; i++) {
    System.out.println(df.format(c.getTime()));
    c.add(Calendar.DATE, 1);
}

Thanks a lot! I really appreciate it as I've been searching for the solution for hours...


public static void main(String[] args) {
    Calendar c = Calendar.getInstance();
    // Set the calendar to monday of the current week
    c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

    // Print dates of the current week starting on Monday to Friday
    DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
    for (int i = 0; i <= 10; i++) {
        System.out.println(df.format(c.getTime()));
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == Calendar.FRIDAY) { // If it's Friday so skip to Monday
            c.add(Calendar.DATE, 3);
        } else if (dayOfWeek == Calendar.SATURDAY) { // If it's Saturday skip to Monday
            c.add(Calendar.DATE, 2);
        } else {
            c.add(Calendar.DATE, 1);
        }

        // As Cute as a ZuZu pet.
        //c.add(Calendar.DATE, dayOfWeek > Calendar.THURSDAY ? (9 - dayOfWeek) : 1);
    }
}

Output

Mon 03/01/2011
Tue 04/01/2011
Wed 05/01/2011
Thu 06/01/2011
Fri 07/01/2011
Mon 10/01/2011
Tue 11/01/2011
Wed 12/01/2011
Thu 13/01/2011
Fri 14/01/2011
Mon 17/01/2011

If you want to be cute you can replace the if/then/else with

c.add(Calendar.DATE, dayOfWeek > 5 ? (9 - dayOfWeek) : 1);

but I really wanted something easily understood and readable.


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<DayOfWeek> 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.

How to check if it's Saturday/Sunday?


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.


Here is short answer using Java 8, all you need to do is to convert your Calendar instance to LocalDateTime and leverage DayOfWeek enum to check if it's Saturday or Sunday, here you go...

Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
        for (int i = 0; i <= 20; i++) {

           //following line does all magic for you
            if(LocalDateTime.ofInstant(c.toInstant(), ZoneId.systemDefault()).getDayOfWeek()!=DayOfWeek.SATURDAY && LocalDateTime.ofInstant(c.toInstant(), ZoneId.systemDefault()).getDayOfWeek()!=DayOfWeek.SUNDAY)

            System.out.println(df.format(c.getTime()));
            c.add(Calendar.DATE, 1);
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜