user3050866
user3050866

Reputation: 33

Java Calendar.DAY_OF_WEEK gives wrong day

What is wrong with the below code? It gives wrong day for any date of the year.

import java.util.Scanner;
import java.util.Calendar;
public class Solution {
    public static String getDay(String d, String m, String y) {

        String[] days = {"SUNDAY", "MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY"};
        Calendar c = Calendar.getInstance();
        c.set(Integer.parseInt(y), Integer.parseInt(m), Integer.parseInt(d)); 
        return days[c.get(Calendar.DAY_OF_WEEK) - 1]; 
    }
public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String m = in.next();
        String d = in.next();
        String y = in.next();

        System.out.println(getDay(d, m, y));
    }
}

Upvotes: 2

Views: 4170

Answers (2)

Anonymous
Anonymous

Reputation: 86389

It’s easiest to have the Scanner read int values rather than strings:

int m = in.nextInt();
int d = in.nextInt();
int y = in.nextInt();

System.out.println(LocalDate.of(y, m, d).getDayOfWeek());

When I feed 5 4 2018 (today’s date), I get FRIDAY, which is correct.

If you must use strings:

DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("M/d/u");

String m = in.next();
String d = in.next();
String y = in.next();

System.out.println(LocalDate.parse(m + '/' + d + '/' + y, dateFormatter).getDayOfWeek());

The Calendar class you were using is long outdated, poorly designed and sometimes cumbersome to work with. Instead, I recommend java.time, the modern Java date and time API. It is so much nicer. For one little thing, it numbers the months of the year in the same way humans do.

Also, the names of the days of the week are built-in, so don’t reinvent the wheel. Your strings coincide with the names of the values of the DayOfWeek enum in java.time, so just print those to get the strings you want. If you don’t want all uppercase or you want the day names in another language, use DayOfWeek.getDisplayName or a DateTimeFormatter.

Link: Oracle tutorial: Date Time explaining how to use java.time.

Upvotes: 4

VeeArr
VeeArr

Reputation: 6188

See the documentation for the Calendar class: https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#set-int-int-int-

The value for month is 0-indexed, so if you provide 3 as the month value, it is interpreted as "April".

Upvotes: 12

Related Questions