Basic Java Calendar usage (gey first day of month)

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Basic Java Calendar usage (gey first day of month)

Post 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.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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:
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post 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 )
Post Reply