java 从用户获取日期输入并将其保存为java中的日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41881501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:13:39  来源:igfitidea点击:

Take date input from user and save it as date in java

javajava.util.scannerjava.util.date

提问by Zachary Dale

I'm trying to take input from user in (dd/mm/yy)format, save it in same format and pass it with getter, setter to another class. I have tried this way:

我正在尝试以(dd/mm/yy)格式从用户那里获取输入,以相同的格式保存它并使用 getter、setter 将其传递给另一个类。我试过这种方式:

This is what I have tried:

这是我尝试过的:

public static void main(String[] args)
{
    Scanner input = new Scanner(System.in);
    SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
    Guest gstObject = new Guest();
    try {
        System.out.println("Enter check-in date (dd/mm/yy):");
        String cindate = input.next();
        Date date1 = myFormat.parse(cindate);
        gstObject.setIndate(date1);
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

With this code I'm getting an exception when I give input in (27012017 or 27 01 2017):

使用此代码,当我在 (27012017 or 27 01 2017) 中输入时出现异常:

java.text.ParseException: Unparseable date: "27"
  at java.text.DateFormat.parse(DateFormat.java:366)
  at edu.lfa.GuestArrayList.main(GuestArrayList.java:49)

Please point out what mistake I have made.

请指出我犯了什么错误。

回答by Darshan Mehta

Here'sjavadoc for next(), this is what it says:

这是javadoc for next(),它是这样说的:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.

从此扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是与分隔符模式匹配的输入。

Default delimiter is space and hence, it only reads 27. You need to read the whole line by using nextLine(). Following should work:

默认分隔符是空格,因此它只读取27. 您需要使用 阅读整行nextLine()。以下应该工作:

System.out.println("Enter check-in date (dd/mm/yy):");
String cindate = input.nextLine();
if(null != cindate && cindate.trim().length() > 0){
    Date date1 = myFormat.parse(cindate);
}

UpdateTo check for nullor empty string, you need to wrap the parsing code inside ifcondition.

更新要检查null或空字符串,您需要将解析代码包装在if条件中。

回答by Basil Bourque

Other answers addressed how to use Scannercorrectly. I'll address some other issues.

其他答案解决了如何Scanner正确使用。我会解决一些其他问题。

java.time

时间

You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. Avoid the java.util.Dateclass like the Plague.

您正在使用麻烦的旧日期时间类,现在是遗留的,被 java.time 类取代。避免java.util.Date像瘟疫这样的课程。

Also, you are inappropriately trying to represent a date-only value with a date+time class.

此外,您不恰当地尝试使用日期+时间类来表示仅日期值。

Instead, use java.time.LocalDate. The LocalDateclass represents a date-only value without time-of-day and without time zone.

相反,使用java.time.LocalDate. 该LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

To parse the user's input, specify a formatting pattern to match exactlythe expected input from your user.

要解析用户的输入,请指定格式模式以与用户的预期输入完全匹配。

DateTimeFormatter f = DateTimeFormatter.parse( "dd/mm/uuuu" );

Parse user input.

解析用户输入。

LocalDate ld = LocalDate.parse( input , f );

On your business class Guest, make the member variable of type LocalDate.

在您的业务类中Guest,将成员变量设为 type LocalDate

To persist the LocalDate, you can serialize to text in standard ISO 8601format. Simply call toString.

要保留LocalDate,您可以序列化为标准ISO 8601格式的文本。只需调用toString.

String output = guest.getLocalDate().toString();

2017-01-23

2017-01-23



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多