Why am I not getting the day of the week that I expect from setting this calendar object?

Edit: Thanks. I understand this much more. This is very confusing when you first start! Thanks for the help. I'm going to leave the question as it is (more downvotes in danger) as it might help others. There are other libraries that seem to recommend for the time being


I am struggling with the Java calendar function - it seems like it is returning incorrect data, the bottom digit should be Thursday according to the calendar, but it returns as Saturday!

Calendar cal = new GregorianCalendar();
       cal.set(2012,2,23); // 0 = January

      String weekdays[]={"sunday","monday", "tuesday", "wednesday","thursday","friday","saturday",};

        Integer Weekdaycurrent1=cal.get(Calendar.DAY_OF_WEEK);
        System.out.println("today is a "+weekdays[Weekdaycurrent1]); //Prints today is Saturday, when it should be a thursday

      

0


source to share


2 answers


To begin with, it is DAY_OF_WEEK

used 1

:

public final static int SUNDAY = 1;

      

Secondly, 2012-03-23

(yes, Mar not Feb), set cal.set(2012, 2, 23)

was Friday



Your code is behaving correctly.

Edited: for those who are too weak to read the question correctly, the call cal.set(2012,2,23)

sets the date to 2012-03-23

because the parameter month

is zero-based (i.e. Jan = 0, Feb = 1, Mar = 2, etc.)

+4


source


Wrong assumption on your part. Read the javadocs:

http://docs.oracle.com/javase/1.4.2/docs/api/constant-values.html#java.util



public static final int SUNDAY          1
public static final int MONDAY          2
public static final int TUESDAY         3
public static final int WEDNESDAY       4
public static final int THURSDAY        5
public static final int FRIDAY          6
public static final int SATURDAY        7

      

+2


source







All Articles