Month is not printed from a date - Java DateFormat

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

    This is because your format is incorrect: you need "MM/dd/yy" for the month, because "mm" is for minutes:

    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);
    

    Prints 8 - 30 - 2011 (because months are zero-based; demo)

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