Month is not printed from a date - Java DateFormat

bigData picture bigData · Sep 26, 2013 · Viewed 48.2k times · Source

How to get month from a date in java :

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

This code return day and year but not month.

output :

0 - 30 - 2011

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Sep 26, 2013

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)