简体   繁体   中英

SimpleDateFormat Wrong value in Java

I'm trying to set a calendar value to it's base (0) to compare it to another value later on. When I tried to print the result I'm getting the month value when using SimpareDateFormat. Any thoughts? and I'm doing it right?

SimpleDateFormat DataDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat DataDateFormatMonth = new SimpleDateFormat("MM");

Calendar cld = Calendar.getInstance();
cld.set(1, 1, 1);

System.out.println(DataDateFormat.format(cld.getTime()));       //  ->  0001-02-01
System.out.println(DataDateFormatMonth.format(cld.getTime()));  //  ->  02      !!!!
System.out.println(cld.get(Calendar.MONTH));                    //  ->  1

Month interval is 0 to 11 in Calendar API.

JAN--->0
.......
DEC--->11

Calendar.MONTH will return an int value (2) which in your case is the value of MM . ie, Calander.MONTH is a constant

breaking down:

System.out.println(cld.get(Calendar.MONTH));                    //  ->  1
Calaender.MONTH--- 2
cld.get(2); will get the value at the given calendar field. (in this case 2, your month field whihc is 1) 

For instance change your last print statement to

 Calendar cld = Calendar.getInstance();
 cld.set(10, 10, 1100); (format is MM,dd,YYYY)
 System.out.println(cld.get(Calendar.YEAR));             

the output will be 10(it will return the month value in the format) as Calendar.YEAR would return 1 .

Month start with 0 in calander . JANUARY -> 0, FEBRUARY -> 1... DECEMBER ->11

From the API of set() Parameters:

  • year - the value used to set the YEAR time field.
  • month - the value used to set the MONTH time field. Month value is 0-based. eg, 0 for January.
  • date - the value used to set the DATE time field.

这就是你想得到的,因为new SimpleDateFormat("MM")将格式化输入日期并仅返回MM值,即月份。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM