Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if it's Saturday/Sunday?

Tags:

java

calendar

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

like image 838
Cristian Avatar asked Jan 09 '11 01:01

Cristian


People also ask

How do you check if a date is a weekend?

How It Works. The WEEKDAY(Date) function will return a number from 1 to 7 depending on what day of the week the date is. What is this? To find the weekend we need to test if WEEKDAY(Date) equals 1 or 7 which means either a Saturday or a Sunday.

How do I count Saturday and Sunday in Excel?

=NETWORKDAYS(A2,B2) Then type Enter key, and you will count the number of workdays excluding Sundays and Saturdays between the two dates.

How do you filter out weekends?

To filter weekdays or weekend days, you apply Excel's filter to your table (Data tab > Filter) and select either "Workday" or "Weekend".

How do I identify a Saturday in Excel?

When given a date, WEEKDAY returns a number 1-7, for each day of the week. In it's standard configuration, Saturday = 7 and Sunday = 1. By using the OR function, use WEEKDAY to test for either 1 or 7.


2 Answers

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.

like image 149
Andrew T Finnell Avatar answered Oct 08 '22 18:10

Andrew T Finnell


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.

enter image description here


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.

like image 37
Basil Bourque Avatar answered Oct 08 '22 18:10

Basil Bourque