java - 使用 LocalDate 获取输入

标签 java localdate dateformatter

大家好!我正在尝试考虑一种使用 LocalDate 从用户那里获取日期输入的方法。我收到一条错误消息“类型不匹配:无法从字符串转换为 LocalDate。”我知道为什么会发生此错误,但我想知道是否有其他方法可以解决此问题。

String newName = stringInput("Enter a product name: ");
String newStore = stringInput("Enter a store name: ");
LocalDate newDate = dateInput("Enter a date (like 3/3/17): ");
double newCost = doubleInput("Enter cost: ");

    /* the third parameter of Purchase2 is a LocalDate which I think is the reason for my error.
     * Is there any way to get around this?
     */
Purchase2 purchase = new Purchase2(newName, newStore, newDate, newCost);
            purchases.add(purchase); // I'm adding these to an ArrayList


    /*
     * This is the method I created for newDate
     * I need to take the date as String and convert it to LocalDate
     */
 public static String dateInput(String userInput) {

    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
    LocalDate date = LocalDate.parse(userInput, dateFormat);


    System.out.println(date);
    return userInput;
}

我对 Java 非常陌生,因此我们将不胜感激!谢谢!

最佳答案

dateInput 的返回值更改为 LocalDate

public static LocalDate dateInput(String userInput) {

    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yyyy");
    LocalDate date = LocalDate.parse(userInput, dateFormat);


    System.out.println(date);
    return date ;
}

并修改:

LocalDate newDate = dateInput(stringInput("Enter a date (like 3/3/17): "));

除此之外,您还需要关心 yyyy 格式化程序

关于java - 使用 LocalDate 获取输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42522744/

相关文章:

java - Eclipse "Debug Current Instruction Pointer"慢

java - Maven导入eclipse时不给项目添加依赖jar文件

java - LocalDate.now() 返回错误的日期

java - 2019-06-17T20 :27:23. 706000000Z 的日期格式是什么?

swift - 如何从格式化的日期字符串中删除 'at'?

java - 具有 get(int index) 和避免重复能力的 O(1) 性能的数据结构

java - 如何使用 Spring Boot 向 iOS 应用程序发送推送通知

ios - 日期格式化程序不从应用程序中的字符串返回日期,但可以在 Playground 上工作

java - 如何使用 Spring Boot 和 Thymeleaf 使用 LocalDate 在两个日期之间进行验证

java - 如何动态自定义日期格式的反序列化器?