Page 1 of 1

Basic Java Calendar usage (gey first day of month)

Posted: Wed Jan 17, 2007 2:04 pm
by Chris Corbyn
I must be going insane. I haven't got a clue why this doesn't work :(

I want to determine what day of the week it was at the 1st of this month (i.e. Monday 1st January)

Code: Select all

//Get the time right now
Calendar calendar = Calendar.getInstance();
//Set it to the first day of whatever month it is now
calendar.set(Calendar.DAY_OF_MONTH, 1);
//Now get the day of the week
int firstDayOfMonthAsDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
Does that look right? So why is the first day of the week being returned as 5? I don't get it; 5 is a Thursday.

The clock and everything on my computer is correct so I must have completely misunderstood how to use the date stuff.

Posted: Wed Jan 17, 2007 2:37 pm
by volka
What does

Code: Select all

import java.text.SimpleDateFormat;

...

int firstDayOfMonthAsDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); 
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM dd, yyyy H:mm zzzz");
sdf.setCalendar(calendar);
System.out.println( sdf.format(calendar.getTime()) );
print?

Posted: Wed Jan 17, 2007 2:44 pm
by Chris Corbyn
volka wrote:What does

Code: Select all

import java.text.SimpleDateFormat;

...

int firstDayOfMonthAsDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); 
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM dd, yyyy H:mm zzzz");
sdf.setCalendar(calendar);
System.out.println( sdf.format(calendar.getTime()) );
print?
I'll run it in a second :) But I realised my own stupidity when I found the year was 3007. I'd used the same calendar instance earlier to create a 2000 year range (don't ask! -- it's scientific app) in a spinner. Stupid me :oops:

Posted: Wed Jan 17, 2007 2:47 pm
by volka
That's why you should try your own code snippet as provided ;)
( I do that only in 9 of 10 cases and there's _always_ an error in the one untested :-S )