CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: date problem

  1. #1
    Join Date
    Apr 2006
    Posts
    587

    date problem

    Code:
            Calendar cal1 = Calendar.getInstance();
            cal1.set(2010, 01, 29);
            Date date = cal1.getTime();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            String strDate = formatter.format(date);
            
            System.out.println("str date.......... " + strDate);
    It prints out

    str date.......... 01/03/2010

    why isnt it printing 29/01/2010

  2. #2
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: date problem

    It pays to read the API docs - Java Calendar months start at 0 for January, so you are formatting the 29th of February for 2010 which isn't a leap year, so it rolls over to the start of the next month.

    If you use the Calendar constants, it will work as expected:
    Code:
    cal1.set(2010, Calendar.JANUARY, 29);
    Unless in communicating with it [a computer] one says exactly what one means, trouble is bound to result...
    A. Turing
    Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  3. #3
    Join Date
    Feb 2008
    Posts
    966

    Re: date problem

    Which I always used to get confused myself since everything else in the calendar class is NOT zero based. A little consistency guys?

    The first month of the year is JANUARY which is 0; the last depends on the number of months in a year.
    The first week of the year, as defined by getFirstDayOfWeek() and getMinimalDaysInFirstWeek(), has value 1
    The first day of the month has value 1.

  4. #4
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: date problem

    Which I always used to get confused myself since everything else in the calendar class is NOT zero based. A little consistency guys?
    The whole of the date/calendar system is a mess, hence people who need to do serious work with dates tend to use a third party implementation such as Joda Time instead.

    I believe a system similar to Joda time (JSR 310) is planned for inclusion in Java release 7 and not before time if you ask me.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured