【问题标题】:Java calendar using LocalDate使用 LocalDate 的 Java 日历
【发布时间】:2026-02-01 07:10:01
【问题描述】:

您好,我的日历有问题。

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Alert;


        errorDialogue = new Alert(Alert.AlertType.ERROR);
        dialogue = new TextInputDialog();
        Group group = new Group();
        Scene scene = new Scene(group, 650, 500);
        readInput();

        centerX = scene.getWidth() / 2;
        centerY = scene.getHeight() / 2;

}

this is the output calendar

【问题讨论】:

  • 你的问题/问题是?
  • 我不知道如何从输入窗口中获取月份和年份,并让日历变得像想要的那样。
  • 欢迎来到 Stack Overflow。恐怕您需要更具体地了解您的问题,以便我们能够为您提供帮助。看来您已经在代码中输入了内容,对吗?该部分是否按预期工作,如果没有,以哪种方式不工作?如果有的话,你能解释一下你制作日历的问题吗?
  • 也请搜索。类似的问题已经被多次询问和回答,因此您很可能会找到一些指导和灵感。
  • 我问你是否可以让你的问题更具体,现在你已经 less 具体了?投票结束。

标签: java javafx calendar java-time yearmonth


【解决方案1】:

YearMonth

使用DateTimeFormatterM/uu 作为模式将input 解析为YearMonth。然后,您可以从中获取月份和年份

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

【讨论】:

  • 我的意思是从我的方法 readInput() 中获取月份和年份
  • @Martina - 我刚刚发布了一个交互式演示,它将帮助您在应用程序中实现它。简而言之,将签名改为private YearMonth readInput(),从返回的YearMonth中获取年月信息。