How check if today is sunday with Java Calendar
I wrote few lines of code whic开发者_StackOverflowh 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");
To avoid making mistakes, you can use Calendar static values for the month, e.g. :
date.set(2010, Calendar.MARCH, 7);
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.
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.)
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++;
Probably because the month is 0-based, so you set April, 7th, which is a Wednesday.
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");
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
cal.DAY_OF_WEEK == cal.SATURDAY || cal.DAY_OF_WEEK == cal.SATURDAY
should be good enough.
精彩评论