How to check if it is Sunday today with Java Calendar

I have written several lines of code that do not work correctly. What for? Could I explain to me?

Calendar date = Calendar.getInstance(); date.set(2010, 03, 7); if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) System.out.println("OK"); 
+6
java date calendar
source share
8 answers

To avoid errors, you can use static calendar values ​​for the month, for example.

 date.set(2010, Calendar.MARCH, 7); 
+12
source share

Number of months from scratch:

 date.set(2010, 2, 7); 

Also don't get the habit of writing numbers with leading zeros. This tells Java (and many other languages) that you want the number to be interpreted as an octal (base 8) constant, not a decimal.

+9
source share

Because April 7th, 2010 is not Sunday. Months start from zero : 0 = January, 1 = February, 2 = March, ...

(Also, note that you used octal, specifying the month [ 03 instead of 3 ]. There is no biggie until you get to September, after which 08 will be an invalid octal number.)

+5
source share

Is this for Euler 19?

If so, here is the tip, a cycle from 1901 to 2000, from months 0 to 11, from days 1-31, and then ask:

 if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && day==1) counter++; 
+4
source share

Probably because the month is based on 0, so you set April 7th, which is Wednesday.

+3
source share

The month value is 0. Java docs for set method of Calendar class .

Also, if you want to check whether there is Sunday today (on the day the program starts :)), you do not need to set anything, because getInstance returns a Calendar object based on the current time in the default time zone with the default locale:

 Calendar date = Calendar.getInstance(); //date.set(2010, 03, 7); if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) System.out.println("OK"); 
+3
source share

For me, this code worked correctly, set the exact date to millisecond and try like this: -

  GregorianCalendar dt = new GregorianCalendar(); dt.setTimeInMillis(getTimestampDDmmYYYY(date).getTime()); if((dt.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY| dt.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)) return true; 

Thank you Prabhat Kumar Kashyap

0
source share

cal.DAY_OF_WEEK == cal.SATURDAY || cal.DAY_OF_WEEK == cal.SATURDAY

should be good enough.

0
source share

All Articles