简体   繁体   中英

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

Edit: Thanks- I understand it a lot more now. Its very confusing when you first start! Thanks for the help. I am going to keep the question up as is ( in peril of more downvotes) as it might help others. There are some other libraries that everyone seems to recommend for date time


I am struggling with the Java calendar function- its seems to be returning wrong data the bottom figure should be a thursday according to calendar, but is returning as a 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

For starters, DAY_OF_WEEK is 1 based:

public final static int SUNDAY = 1;

Secondly, 2012-03-23 (yes, Mar not Feb) as set by cal.set(2012, 2, 23) was a Friday

Your code is behaving correctly.

Edited: For those too lame to read the question properly, calling cal.set(2012,2,23) sets the date to 2012-03-23 , because the month parameter is zero-based (ie Jan = 0, Feb = 1, Mar = 2, etc)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM