Search code examples
javadatecalendardayofweekjava.util.calendar

How can I take a user inputted date instead of the current date in the Calendar class in Java?


I'm working on an assignment, and my goal is to create a class that prints the day of the week given a date. When prompted for input, if the user enters nothing, the program is stopped. Otherwise, if the user enters a date, the program provides the day of the week and then continues to re-prompt the user. The date the user inputs will be in the format of m d y, or for example, 1 10 2017 for January 10th, 2017.

What I have so far does everything I need, except it uses the current day, month, and year instead of the user inputted day, month, and year.

import java.util.Calendar;
import java.util.Scanner;

public class FindDayOfWeek {

public static void main(String[] args) {
    Scanner s = new Scanner(System.in);
    System.out.println("Repeatedly enter a date (m d y) to get the day of week. Terminate input with a blank line.");
    String date = s.nextLine();

    while (true) {

        if (date.isEmpty()) {
            System.exit(0);
        }

        else {  

            Calendar c = Calendar.getInstance();

            String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

            System.out.println("Day of week is " + days[c.get(Calendar.DAY_OF_WEEK) - 1]);

            System.out.println("Repeatedly enter a date (m d y) to get the day of week. Terminate input with a blank line.");
            date = s.nextLine();
        }
      }
    }
  }

I know what needs to be replaced is the second to last chunk of code that says c.get(Calendar.DAY_OF_WEEK), however I do not know what I can use to replace it in order to get the user inputted date.

I know there are other packages that can solve the same problem, however, I'm required to use the Calendar class whether I like it or not.


Solution

  • Don't use Calendar use the java.time package instead:

    import java.util.Scanner;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    
    class Main {
      public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
        LocalDate inputDate;
    
        while(true){
          System.out.print("Enter a date in the format of MM/dd/yyyy:");
          String date = scanner.next();
          try {
            inputDate = LocalDate.parse(date, formatter);
            break;
          } catch (Exception e) {
            System.err.println("ERROR: Please input the date in the correct format");
          }
        }
    
        System.out.println("The day of week is " + inputDate.getDayOfWeek().name());
      }
    }
    

    Example Usage:

    Enter a date in the format of MM/dd/yyyy: 92/23/2344
    ERROR: Please input the date in the correct format
    Enter a date in the format of MM/dd/yyyy: 11/26/2019
    The day of week is TUESDAY
    

    However if you really need to use Calendar and want to use something resembling your existing code, try this:

    N.B. Pay attention to the line formatter.setLenient(false); which ensures strict parsing, such that input must match the EXACT format.

    import java.util.Scanner;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.text.ParseException;
    import java.util.Calendar;
    
    class Main {
      public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        formatter.setLenient(false);
        Date inputDate;
    
        while(true){
          System.out.print("Enter a date in the format of MM/dd/yyyy:");
          String date = scanner.nextLine();
          try {
            inputDate = formatter.parse(date);
            break;
          } catch (Exception e) {
            System.err.println("ERROR: Please input the date in the correct format");
          }
        }
    
        Calendar c = Calendar.getInstance();
        c.setTime(inputDate);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        String[] days = new String[] {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
    
        System.out.println("The day of week is " + days[dayOfWeek - 1]);
      }
    }
    

    Example Usage:

    Enter a date in the format of MM/dd/yyyy: 92/23/2344
    ERROR: Please input the date in the correct format
    Enter a date in the format of MM/dd/yyyy: 11/26/2019
    The day of week is Tuesday