解析input
为YearMonth
使用DateTimeFormatter
withM/uu
作为模式。然后,您可以从中获取月份和年份
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
String input = "03/21";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/uu");
YearMonth ym = YearMonth.parse(input, dtf);
System.out.println("Month: " + ym.getMonthValue());
System.out.println("Year: " + ym.getYear());
}
}
输出:
Month: 3
Year: 2021
从Trail: Date Time了解有关现代日期时间 API 的更多信息。
交互式演示:
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
YearMonth ym = readInput();
System.out.printf(String.format("Month: %d, Year: %d%n", ym.getMonthValue(), ym.getYear()));
}
static YearMonth readInput() {
Scanner scanner = new Scanner(System.in);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/uu");
boolean valid;
YearMonth ym = null;
do {
valid = true;
System.out.print("Enter month and year [MM/yy]: ");
String input = scanner.nextLine();
try {
ym = YearMonth.parse(input, dtf);
} catch (DateTimeParseException e) {
System.out.println("This is an invalid input. Please try again.");
valid = false;
}
} while (!valid);
return ym;
}
}
示例运行:
Enter month and year [MM/yy]: a/b
This is an invalid input. Please try again.
Enter month and year [MM/yy]: 21/3
This is an invalid input. Please try again.
Enter month and year [MM/yy]: 3/21
Month: 3, Year: 2021