gifpif
gifpif

Reputation: 4917

In my code why date of month are different in Java Date or Calendar?

Here is my code.

Calendar calendar= Calendar.getInstance();
    System.out.println("Calender: "+calendar);
    System.out.println("Calender Date: "+calendar.DAY_OF_MONTH);
    System.out.println("Date: "+new Date().getDate());

Output:

enter image description here

In red box Calendar show DAY_OF_MONTH=14, but calendar.DAY_OF_MONTH show 5.

Upvotes: 2

Views: 79

Answers (6)

Frank Shao
Frank Shao

Reputation: 19

System.out.println("Calender Date: "+calendar.DAY_OF_MONTH);

You just get the constant field value for DAY_OF_MONTH from Calendar,

it's not the actual day ,so you get two different results,

if you want to get the actual day of month,you can do this:

calendar.get(Calendar.DAY_OF_MONTH)

Upvotes: 1

Andy Turner
Andy Turner

Reputation: 140524

You should use calendar.get(Calendar.DAY_OF_MONTH) instead. You are currently printing out a constant in the Calendar class used to get the field's value in a given instance.

Upvotes: 1

Jens
Jens

Reputation: 69480

calendar.DAY_OF_MONTH is only a key. The DAY_OF_MONTH from Calendar you get via calendar.get(Calendar.DAY_OF_MONTH)

Upvotes: 3

Smutje
Smutje

Reputation: 18173

Yes, because you are accessing the constant field value for DAY_OF_MONTH and not the actual day of month.

Upvotes: 2

Scary Wombat
Scary Wombat

Reputation: 44854

what you are printing here

System.out.println("Calender Date: "+calendar.DAY_OF_MONTH);

is the value of the constant DAY_OF_MONTH

The correct way to get the value is calendar.get(Calendar.DAY_OF_MONTH)

Upvotes: 4

Duncan Jones
Duncan Jones

Reputation: 69399

Calendar.DAY_OF_MONTH is a constant value, which points at the day of the month field.

To get the actual value, you'd need to call:

calendar.get(Calendar.DAY_OF_MONTH)

Upvotes: 4

Related Questions