Month is not printed from a date - Java DateFormat

前端 未结 7 1245
滥情空心
滥情空心 2020-12-02 00:18

How to get month from a date in java :

        DateFormat inputDF  = new SimpleDateFormat(\"mm/dd/yy\");
        Date date1 = inputDF.parse(\"9/30/11\");

          


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 00:52

    First, you used mm in your date format, which is "minutes" according to the Javadocs. You set the minutes to 9, not the month. It looks like the month defaults to 0 (January).

    Use MM (capital 'M's) to parse the month. Then, you will see 8, because in Calendar months start with 0, not 1. Add 1 to get back the desired 9.

    The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0

    // MM is month, mm is minutes
    DateFormat inputDF  = new SimpleDateFormat("MM/dd/yy");  
    

    and later

    int month = cal.get(Calendar.MONTH) + 1; // To shift range from 0-11 to 1-12
    

提交回复
热议问题