Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the setMonth method of Java Calendar work wrong?

Tags:

java

calendar

I have small code such as below. I expected that the result should be 7, but it printed 6. If I uncomment the line tmp.get(Calendar.MONTH), it runs OK (prints 7).

Please let me know the reason. I'm using JDK 1.7.0_25 in MacOS.

public static void main(String[] args) {
    Calendar tmp = Calendar.getInstance();
    tmp.set(Calendar.DAY_OF_MONTH, 4);
    tmp.set(Calendar.MONTH, Calendar.AUGUST);
    //tmp.get(Calendar.MONTH);
    tmp.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    System.out.println(tmp.get(Calendar.MONTH));
}

Screenshot:
Comment code: http://gyazo.com/4c099b1b2b90d72d1954b98b134e4ac3
Uncomment code: http://gyazo.com/fe368745da168646140ca9f3a60d2021

like image 311
nhthai Avatar asked Jul 04 '15 10:07

nhthai


3 Answers

Because month index starts with index 0. add +1 while get month. it is c based structure copied into java. It has indexes 0 to 11.

And i think day of month is incorrect. comment that and run it it shows correctly.(tmp.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);)

    tmp.set(Calendar.DAY_OF_MONTH, 4);
    tmp.set(Calendar.MONTH, Calendar.AUGUST);
    //tmp.get(Calendar.MONTH);
    //tmp.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    System.out.println(tmp.get(Calendar.MONTH));

By default it takes year as 2015 and August 4 is tuesday not monday

like image 127
Buru Avatar answered Oct 18 '22 14:10

Buru


I tried to run your code and it prints 7 every time (even tried to uncomment that line you mention). Which seems correct to me.

EDIT The problem is explained in detail Java Calendar - Date is unpredictable after setting day_of_week

I am glad that with Java 8 came new API for working with date and time.

EDIT2

My understanding of what happened:

Only sensible combinations are

YEAR + MONTH + DATE (let's call it A)

or

YEAR + MONTH + WEEK_OF_MONTH + DAY_OF_WEEK (let's call it B)

And the Calendar has its inner state of date in which he thinks he is. So basically before you set

DAY_OF_WEEK

you were working with combination A but after it you were working with combination B and this line

tmp.set(Calendar.DAY_OF_MONTH, 4);

was ignored. Thus it took Monday in the first week of August (2015-07-27). But when you called

tmp.get(Calendar.MONTH);

you "materialized" the date according to combination A (so to 2015-08-04) and the

DAY_OF_WEEK

was set "correctly" starting from 2015-08-04.

Anyway could you try that with JDK 8?

like image 44
jakub.petr Avatar answered Oct 18 '22 13:10

jakub.petr


When you set DAY_OF_WEEK = MONDAY, Calendar returns back to last Monday and it is 27th of Jul, you can check it with System.out.println(tmp.get(Calendar.DAY_OF_MONTH));

like image 36
Evgeniy Dorofeev Avatar answered Oct 18 '22 12:10

Evgeniy Dorofeev