Problems with Calendar.get(Calendar.DAY_OF_WEEK)

I need to know wich day of the week is a given date, i mean, the user gives me 05.03.2007 and i need to know if it's Saturday.

To know it, i do this:

GregorianCalendar calendario = new GregorianCalendar();

calendario.clear();

calendario.setFirstDayOfWeek(6);

calendario.set(calendario.MONTH, month);

calendario.set(calendario.DAY_OF_MONTH, day);

calendario.set(calendario.YEAR, year);

//month, day and year are int variable wich contains the given date.

day = calendario.get(calendario.DAY_OF_WEEK);

system.out.println("Wich day is it?-> "+day);

This code, seems to work, but if you set the "today" date (month=5, day=4, year=2007) it prints: "Wich day is it?->2" wich is Tuesday (and today is friday!)

What's happening? I'm using JDK 1.4

[837 byte] By [misatoa] at [2007-11-27 3:22:19]
# 1

Is it necessary for your code to set what the first day of the week is?

This is similar code, but shorter. I don't know if it will make the difference, but worth a shot.

GregorianCalendar calendario = new GregorianCalendar (year, month, date);

day = calendario.get(calendario.DAY_OF_WEEK);

system.out.println("Wich day is it?-> "+day);

kdajania at 2007-7-12 8:25:05 > top of Java-index,Java Essentials,Java Programming...
# 2

It's not necessary to set what the first day of week is, it's just to try if it makes any difference (and i forgot not to paste it here :P)

I didn't see the constructor has the option to set the date in it, thanks (that will make my code simple and cleaner than now)

Let me try it.

misatoa at 2007-7-12 8:25:05 > top of Java-index,Java Essentials,Java Programming...
# 3
It makes the same result... number 2 (wich is Tuesday isn't it?) for today
misatoa at 2007-7-12 8:25:05 > top of Java-index,Java Essentials,Java Programming...
# 4

It probably wasn't obvious to you that Java numbers the months starting at zero. But it does. So month number 5 is June, and you are asking about 2007 June 4. However if you use SimpleDateFormat's parse() method you don't have to know ugly details like that.

And what you get from the Calendar.get() method is not to be interpreted as 2. It is to be interpreted as the constant value Calendar.MONDAY (whose value happens to be 2).

Spend some time reading the API documentation for the Calendar class, it's not all as intuitive as you hoped. Writing code to test things doesn't hurt, but if you read the documentation first then you aren't just shooting wildly in the dark.

And doesn't 05.03.2007 mean 5 March 2007?

DrClapa at 2007-7-12 8:25:05 > top of Java-index,Java Essentials,Java Programming...
# 5
Yes! I forgot that months started in 0 instead of 1 (i was considering January 1 not 0)Now it works.By the way, i was writting the date in month.day.year format, so 05.03.2007 is 3 May.2007 fot me. Sorry for the confussionAnd thanks for everything
misatoa at 2007-7-12 8:25:05 > top of Java-index,Java Essentials,Java Programming...