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
mm
is for minutes, useMM
while specifying format.Month format should be
MM
instead ofmm
This is because your format is incorrect: you need
"MM/dd/yy"
for the month, because"mm"
is for minutes:Prints
8 - 30 - 2011
(because months are zero-based; demo)First, you used
mm
in your date format, which is "minutes" according to the Javadocs. You set the minutes to9
, not the month. It looks like the month defaults to 0 (January).Use
MM
(capital 'M's) to parse the month. Then, you will see8
, because inCalendar
months start with 0, not 1. Add1
to get back the desired9
.and later
Try like this using
MM
instead ofmm
:-The month printed will be 8 as index starts from 0
or try with:-
If you read the
SimpleDateFormat
javadoc, you'll notice thatmm
is for minutes. You needMM
for month.Otherwise the format doesn't read a
month
field and assumes a value of0
.