Does anyone know why I get the output below? I expected 2012-12 instead of 2013-12
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,2012);
cal.set(Calendar.MONTH,12-1);
cal.set(Calendar.DATE,30);
Date date=cal.getTime();
System.out.println(date);
String YYYY_MM=format.format(date);
System.out.println(YYYY_MM);
OUTPUT
Sun Dec 30 18:30:52 KST 2012
2013-12
EXPECTED
Sun Dec 30 18:30:52 KST 2012
2012-12
You are using incorrect date formatter. You can try this way,
Calendar cal=Calendar.getInstance();
cal.set(Calendar.YEAR,2012);
cal.set(Calendar.MONTH,12-1);
cal.set(Calendar.DATE,30);
Date date=cal.getTime();
System.out.println(date);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM");
// Java SimpleDateFormat use `yyyy` (lowercase) not `YYYY`(uppercase)
String YYYY_MM=format.format(date);
System.out.println(YYYY_MM); //out put 2012-12
Out put for me
Sun Dec 30 15:20:08 IST 2012
2012-12
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.