Reputation: 498
I wrote few lines of code which doesn't work correctly. Why? Could sb explain me?
Calendar date = Calendar.getInstance();
date.set(2010, 03, 7);
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY)
System.out.println("OK");
Upvotes: 6
Views: 22285
Reputation: 25969
cal.DAY_OF_WEEK == cal.SATURDAY || cal.DAY_OF_WEEK == cal.SATURDAY
should be good enough.
Upvotes: 0
Reputation: 11
For me this code worked properly, please set the exact date by it 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;
Thanks, Prabhat Kumar Kashyap
Upvotes: 0
Reputation: 1074058
Because April 7th, 2010 isn't a Sunday. Months start with zero: 0 = January, 1 = February, 2 = March, ...
(Also, side note, you've used octal when specifying the month [03
instead of 3
]. No biggie until you get to September, whereupon 08
is an invalid octal number.)
Upvotes: 5
Reputation: 9680
Is this for Euler 19?
If so, here is a tip, loop from 1901 to 2000, from months 0 to 11, from days 1-31, then ask:
if(date.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && day==1)
counter++;
Upvotes: 4
Reputation: 7090
To avoid making mistakes, you can use Calendar static values for the month, e.g. :
date.set(2010, Calendar.MARCH, 7);
Upvotes: 12
Reputation: 454960
The month value is 0-based. Java docs for set method of Calendar class
.
Also if you want to check if today(the day the program is run :) ) is Sunday, you need not set anything, because the getInstance
method 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");
Upvotes: 3
Reputation: 262474
Probably because the month is 0-based, so you set April, 7th, which is a Wednesday.
Upvotes: 3
Reputation: 413702
Months count from zero:
date.set(2010, 2, 7);
Also don't get in the habit of writing numbers with leading zeros. That tells Java (and many other languages) that you want the number interpreted as an octal (base 8) constant, not decimal.
Upvotes: 9