Java Calendar date error

前端 未结 5 1879
栀梦
栀梦 2021-01-26 02:41

Can anyone please help me understand why I am getting different month values for

SimpleDateFormat dateFormat = new SimpleDateFormat(\"dd/MM/yyyy\");    
Syst         


        
相关标签:
5条回答
  • 2021-01-26 02:43

    Months in Calendar starts in 0

    0 讨论(0)
  • 2021-01-26 02:52

    Calendar.MONTH return 0-based values i.e. JANUARY is represented with 0. That way SEPTEMBER is 8.

    0 讨论(0)
  • 2021-01-26 02:59

    Your likely problem is that Calendar uses a zero-based index for months. So the format correctly outputs 9 for September, but the getter returns 8.

    Is this stupid and inconsistent of Calendar? Yes! Use the Joda-Time API for working with dates and times instead. As far as I'm aware, it's currently the de-facto standard until JSR 310 comes around.

    0 讨论(0)
  • 2021-01-26 03:05

    The other answers are correct. The java.util.Calendar class uses zero-based counting for month numbers. One of many reasons to avoid using the java.util.Date/Calendar classes.

    This kind of work is easier with the Joda-Time 2.3 library. Thankfully it sensibly uses one-based counting such as January = 1, December = 12.

    java.util.Calendar cal = java.util.Calendar.getInstance();
    
    // Though not required here for this one purpose, it's better to specify a time zone than rely on default.
    DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
    DateTime dateTime = new DateTime( cal.getTime(), timeZone );
    
    // Extract month. Note how these two lines call similar sounding methods that are actually quite different.
    // One returns a primitive int value. The other returns an object of nested class DateTime.Property.
    int monthNumber = dateTime.getMonthOfYear();
    String monthName = dateTime.monthOfYear().getAsText( Locale.FRENCH );
    

    Dump to console…

    System.out.println( "dateTime: " + dateTime );
    System.out.println( "monthNumber: " + monthNumber );
    System.out.println( "monthName: " + monthName );
    

    When run…

    dateTime: 2014-02-10T02:58:35.386-05:00
    monthNumber: 2
    monthName: février
    
    0 讨论(0)
  • 2021-01-26 03:07

    In Calendar class, MONTH start from index 0. So, January is 0, February is 1, and hence September is 8.

    P.S.: - That's true that this is an Inconsistency in Calendar class, so I would suggest you to take a look at Joda-Time API to make your life easier while working with date-time data.

    0 讨论(0)
提交回复
热议问题