Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 280
Ahmad Th Avatar asked Aug 12 '26 23:08

Ahmad Th


2 Answers

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 . i.e., 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.

like image 160
PermGenError Avatar answered Aug 14 '26 23:08

PermGenError


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

like image 26
Subhrajyoti Majumder Avatar answered Aug 15 '26 00:08

Subhrajyoti Majumder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!