Faisal Qureshi
Faisal Qureshi

Reputation: 37

Why is Java Calendar reporting the incorrect date?

Could anyone let me know why the following is displaying '5' in the console when it is the 22nd today (UK)?!

System.out.println(Calendar.DAY_OF_MONTH);

Thanks in advance!

Upvotes: 2

Views: 3966

Answers (4)

Aviram Segal
Aviram Segal

Reputation: 11120

Calendar.DAY_OF_MONTH is a constant used for various operations (and happens to be its value is 5), you should be using:

Calendar.getInstance().get(Calendar.DAY_OF_MONTH);

Upvotes: 12

Dheeraj Arora
Dheeraj Arora

Reputation: 608

Calendar.DAY_OF_MONTH or any other Calendar constants are not automatically set to the date, so return their default values.

public final static int DAY_OF_MONTH = 5;

Upvotes: 0

Tom Leese
Tom Leese

Reputation: 19729

You need to construct a calendar instance, then use that static field to look up the day of the month.

Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240996

This is static field used inside Calendar class, you want the following

calendarInstance.get(Calendar.DAY_OF_MONTH);

See

Upvotes: 4

Related Questions