java - 如何从字符串中解析时间?

标签 java parsing time localtime

我正在尝试使用扫描仪将字符串 (11:23) 解析为 LocalDateTime,但出现异常: 无法解析文本“11:23”:无法从 TemporalAccessor 获取 LocalDateTime:{},ISO 解析为 java.time.format.Parsed 类型的 11:23

 Scanner scanner = new Scanner(System.in);
 String timeGivenByUserString;
 DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");

  System.out.println("Type the time HH:mm");
        try {

            do {
                timeGivenByUserString = scanner.nextLine();
            } while (!timeGivenByUserString.matches("\\d{2}:\\d{2}"));
            LocalDateTime timeGivenByUser = LocalDateTime.parse(timeGivenByUserString, timeFormatter);
            System.out.println(timeGivenByUser.format(timeFormatter));

        } catch (DateTimeParseException e) {
            System.out.println(e.getMessage());
        }



我也创建了类似的方法,它工作得很好:


    private static void askAboutDate() {
        Scanner scanner = new Scanner(System.in);
        String dateGivenByUserString;
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");

        System.out.println("Type the date dd.MM.yyyy");
        try {

            do {
                dateGivenByUserString = scanner.nextLine();
            } while (!dateGivenByUserString.matches("\\d{2}.\\d{2}.\\d{4}"));
            LocalDate dateGivenByUser = LocalDate.parse(dateGivenByUserString, dateFormatter);
            System.out.println(dateGivenByUser.format(dateFormatter));

        } catch (DateTimeParseException e) {
            System.out.println(e.getMessage());
        }
    }

最佳答案

解决方案: 将 LocalDateTime 更改为 LocalTime

  Scanner scanner = new Scanner(System.in);
        String timeGivenByUserString;
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm");

        System.out.println("Type the time HH:mm");
        try {

            do {
                timeGivenByUserString = scanner.nextLine();
            } while (!timeGivenByUserString.matches("\\d{2}:\\d{2}"));
            LocalTime timeGivenByUser = LocalTime.parse(timeGivenByUserString, timeFormatter);
            System.out.println(timeGivenByUser.format(timeFormatter));

        } catch (DateTimeParseException e) {
            System.out.println(e.getMessage());
        }

关于java - 如何从字符串中解析时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59599245/

相关文章:

java - 如何确定在 Linux 上使用 Java 还是 JRuby 是否正在运行不同的进程 ID?

java - 全类覆盖单元测试

java - 无法调整 headless Chrome 的大小

JavaScript:删除 HTML 标签、修改标签/文本以及将标签重新插入

java - 以下循环的(最坏情况)时间分析是什么?

php - 使用 PHP 修剪/正确显示 Time MySQL 数据类型

Java Spark : com. mongodb.spark.config.writeconfig 问题

javascript - AngularJS 显示为纯文本

java - ANTLR4 - 嵌套函数中的参数

Python 检查白天