如何在 Java 的日历 class 中使用用户输入的日期而不是当前日期?

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

我正在做一项作业,我的目标是创建一个 class 来打印给定日期的星期几。当提示输入时,如果用户未输入任何内容,程序将停止。否则,如果用户输入日期,程序会提供星期几,然后继续重新提示用户。用户输入的日期格式为 m d y,例如 1 10 2017 表示 2017 年 1 月 10 日。

到目前为止,我所拥有的一切都满足了我的需要,除了它使用当前的日、月和年而不是用户输入的日、月和年。

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();
        }
      }
    }
  }

我知道需要替换的是倒数第二个代码块 c.get(Calendar.DAY_OF_WEEK),但是我不知道我可以用什么来替换它以便获取用户输入的日期。

我知道还有其他软件包可以解决同样的问题,但是,无论我喜不喜欢,我都必须使用日历 class。

不要使用日历,而是使用 java.time 包:

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());
  }
}

用法示例:

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

但是,如果您确实需要使用 Calendar 并希望使用与现有代码类似的东西,请尝试以下操作:

N.B. 注意确保严格解析的行 formatter.setLenient(false);,这样输入必须匹配 EXACT 格式。

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]);
  }
}

用法示例:

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

尽量减少使用过时的API

是正确的,在推荐 java.time 而不是您需要使用的早已过时的 Calendar class 时也是如此。我只想在这里补充一点:虽然你必须使用Calendar class,但并不一定意味着你也需要使用它的过时朋友DateSimpleDateFormat。后者可能是其中最麻烦的,当然也是要避免的。

    DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M d u");
    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();
    LocalDate ld = LocalDate.parse(date, inputFormatter);

    // the easy way to get day-of-week would be ld.getDayOfWeek(),
    // but we are required to use Calendar
    // (any ZoneId will do for atStartOfDay(), I just prefer to provide one)
    Calendar c = GregorianCalendar.from(ld.atStartOfDay(ZoneOffset.UTC));
    int numberOfDayOfWeek = c.get(Calendar.DAY_OF_WEEK);

    // display
    DayOfWeek dayOfWeek;
    // Calendar’s dayOfWeek starts from 1 = Sunday;
    // for DayOfWeek.of() we need to start from 1 = Monday
    if (numberOfDayOfWeek == Calendar.SUNDAY) {
        dayOfWeek = DayOfWeek.SUNDAY;
    } else {
        dayOfWeek = DayOfWeek.of(numberOfDayOfWeek - 1);
    }
    System.out.println("Day of week is "
            + dayOfWeek.getDisplayName(TextStyle.FULL_STANDALONE, Locale.US));

示例会话:

Repeatedly enter a date (m d y) to get the day of week. Terminate input with a blank line.
10 5 2017
Day of week is Thursday

我省略了重复,直到输入了一个空行,因为你似乎已经处理好了。

虽然以上肯定不是您的导师所追求的,但在现实生活中,使用特定过时 class 的要求通常来自使用需要 and/or 的遗留 API给你一个旧 class 的实例。在这种情况下,我建议您尽量减少使用旧的 API 并尽可能使用现代的。因此,在代码中,我仅在找到星期几之前的最后一刻才转换为 Calendar 。无论您是从 Date 转换为 Calendar 还是从 LocalDate 转换为 Calendar 都不会对代码的复杂性产生任何重大影响,因此您不妨自己做赞成使用现代 LocalDate.

我确实通过从 intCalendar 转换回现代 DayOfWeek 枚举来增加一些额外的复杂性,我用它来显示日期名称。如果你愿意,你可以省略这部分。我包含它只是为了证明在从 int 转换为日期名称时有一种方法可以避免重新发明轮子。