-1

I need the code to take a date in the format mm dd yyyy (via standard input) and output the week day in plain English.

Sample input (mm dd yyyy): 09 23 2016

Expected output: FRIDAY

Incorrect output: SUNDAY

Can anyone please explain what's going wrong here? Thank you.

import java.io.*;
import java.util.*;
import java.time.*;

public class DateToDay {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int month = Integer.parseInt(in.next());
        int day = Integer.parseInt(in.next());
        int year = Integer.parseInt(in.next());

        if ((year > 2000) && (year < 3000)) {
            Calendar cal = Calendar.getInstance();
            Locale locale = Locale.getDefault();

            cal.set(Calendar.MONTH, month);
            cal.set(Calendar.DAY_OF_MONTH, day);
            cal.set(Calendar.YEAR, year);

            System.out.println(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, locale).toUpperCase());
        }
        else {
            System.out.println("Invalid date entered.");
        }
    }
}
Jens
  • 67,715
  • 15
  • 98
  • 113
MAK
  • 125
  • 2
  • 13

3 Answers3

4

Calendar.Month is Zero based:

MONTH public static final int MONTH

Field number for get and set indicating the month. This is a calendar-specific value. The first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last depends on the number of months in a year. See Also:

So 9 is october and oct 23 2016 is a sunday. So you have to use cal.set(Calendar.MONTH, month-1);

if you are using java8 you can simply use the new DateTime API:

LocalDate date = LocalDate.of(year, month, day);
System.out.println(date.getDayOfWeek());
Jens
  • 67,715
  • 15
  • 98
  • 113
1
 Scanner in = new Scanner(System.in);
    int month = Integer.parseInt(in.next());
    int day = Integer.parseInt(in.next());
    int year = Integer.parseInt(in.next());

    if ((year > 2000) && (year < 3000)) {
        Calendar cal = Calendar.getInstance();
        Locale locale = Locale.getDefault();

        cal.set(Calendar.MONTH, month-1);
        cal.set(Calendar.DAY_OF_MONTH, day);
        cal.set(Calendar.YEAR, year);

        System.out.println(cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, locale).toUpperCase());
    }
    else {
        System.out.println("Invalid date entered.");
    }
bhanu avinash
  • 484
  • 2
  • 16
1

The problem is in here.

cal.set(Calendar.MONTH, month);

If Calendar.MONTH is 0, the month is January.

If Calendar.MONTH is 1, the month is February.

If Calendar.MONTH is 2, the month is March, and so on.

So, when you enter 09 as an input, the Calendar.MONTH becomes October, not September. This is because, as explained above, Calendar.MONTH starts from 0.

Try this instead:

cal.set(Calendar.MONTH, month-1);
codemirel
  • 160
  • 10