Month is not printed from a date - Java DateFormat

前端 未结 7 1228
滥情空心
滥情空心 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:38

    Try like this using MM instead of mm:-

        DateFormat inputDF  = new SimpleDateFormat("MM/dd/yy");
        Date date1 = inputDF.parse("9/30/11");
    
        Calendar cal = Calendar.getInstance();
        cal.setTime(date1);
    
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        int year = cal.get(Calendar.YEAR);
    
        System.out.println(month+" - "+day+" - "+year);
    

    The month printed will be 8 as index starts from 0

    or try with:-

    int month = cal.get(Calendar.MONTH) + 1;
    

提交回复
热议问题