Java Calendar usage



  • Hi, I had to write a small java method to convert a date into a progressive day of the year.

    I used the GregorianCalendar in this way:

    cal.clear();

    cal.set(year,month,day); //where year,month,day are 2006, 1,1 for testing purpose

    cal.get(Calendar.DAY_OF_YEAR);

     
    and the result is 32, WTF?  But if I use cal.get(Calendar.YEAR); cal.get(Calendar.MONTH); cal.get(Calendar.DATE); I get correct values.

    I also tried with 2006 11 16 and I get 350, wich seems to be wrong.

    Am I missing something?

     

    BTW, I solved the issue using

    cal.clear();
    cal.setTime(new SimpleDateFormat("yyyyMMdd").parse("20061116"));
    cal.get(Calendar.DAY_OF_YEAR);


    surrounded by a try block to catch a FormatException, that is, passing to cal a Date Object created using an input string.

    Why is the other way wrong? Just curiosity...

     

    Thanks guys!
     

     

     

     



  • set

    public final void set(int year,
    int month,
    int date)
    Sets the values for the fields year, month, and date. Previous values of other fields are retained. If this is not desired, call clear first.

     

    Parameters:
    year - the value used to set the YEAR time field.
    month - the value used to set the MONTH time field. Month value is 0-based. e.g., 0 for January.
    date - the value used to set the DATE time field.



  • [quote user="Zigo"]

    Hi, I had to write a small java method to convert a date into a progressive day of the year.

    I used the GregorianCalendar in this way:

    cal.clear();

    cal.set(year,month,day); //where year,month,day are 2006, 1,1 for testing purpose

    cal.get(Calendar.DAY_OF_YEAR);


    and the result is 32, WTF?  But if I use cal.get(Calendar.YEAR); cal.get(Calendar.MONTH); cal.get(Calendar.DATE); I get correct values.

    I also tried with 2006 11 16 and I get 350, wich seems to be wrong.

    Am I missing something?

    [/quote]

     These are correct. When you set the date using cal.set(2006,1,1) you are setting the date to Feb 1 2006, not Jan 1 2006, so the day of year is 32 (31 days in jan, +1 for Feb 1) and

    cal.set(2006,11,15) sets the date to Dec 15 2006, thus the 350 th day of the year.

     

    SE



  • OK, understood!

     

    THX a lot guys! 



  • [quote user="Zigo"]

    OK, understood!

     

    THX a lot guys! 

    [/quote]

    calendar.set(2006, Calendar.JANUARY, 0);

     

     


Log in to reply
 

Looks like your connection to What the Daily WTF? was lost, please wait while we try to reconnect.