使用LocalDate获取输入

时间:2017-03-01 03:39:13

标签: java localdate dateformatter

大家好!我试图想办法使用LocalDate从用户那里获得日期输入。我收到一个错误,上面写着“类型不匹配:无法从String转换为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新手,所以任何帮助都将受到赞赏!谢谢!

1 个答案:

答案 0 :(得分:2)

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格式化程序