user2391218
user2391218

Reputation: 412

finding the day based on date in java - gives incorrect answer

java.util.Date gives incorrect day as output.

    java.util.Date date = new Date(2014,03,01);
    System.out.println("day is" +date.getDay());

output : day is 3

actually it should be 7

Update : Thanks a lot I was able to get the output Here is my code

    java.util.Calendar c = java.util.Calendar.getInstance();
    c.clear();
    c.set(year,month,dd);
    System.out.println("day of week "+c.get(java.util.Calendar.DAY_OF_WEEK));

Upvotes: 0

Views: 499

Answers (2)

sanbhat
sanbhat

Reputation: 17622

As per the javadoc of getDay()

Returns the day of the week represented by this date. The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or begins with the instant in time represented by this Date object, as interpreted in the local time zone.

so its not day of month. Also note that you are using deprecated Date constructor and methods. You can achieve the same using java.util.Calendar

Also month 03 is not March, its April

    Calendar c = Calendar.getInstance();
    c.set(Calendar.YEAR, 2014);
    c.set(Calendar.MONTH, 3);
    c.set(Calendar.DAY_OF_MONTH, 1);

    System.out.println(c.get(Calendar.DAY_OF_WEEK));

Here also the output is 3 because, the date represents April 1st 2014, which is Tuesday and as per Calendar.DAY_OF_WEEK doc

Field number for get and set indicating the day of the week. This field takes values SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

And Calendar.TUESDAY is 3

Upvotes: 2

Andreas Wilkes
Andreas Wilkes

Reputation: 1041

I guess you wanted to create the date March 1st 2014. But with your constructor call you create the date April 1st 3914! The API tells you why:

A year y is represented by the integer y - 1900.
A month is represented by an integer from 0 to 11; 0 is January, 1 is February, and so forth; thus 11 is December.
A date (day of month) is represented by an integer from 1 to 31 in the usual manner.

EDIT: Also this constructor is deprecated. Use Calendar instead.

Upvotes: 5

Related Questions