Java 将字符串转换为 GregorianCalendar

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2331513/
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-08-13 06:14:16  来源:igfitidea点击:

Convert a string to a GregorianCalendar

javastringgregorian-calendar

提问by Kat

How do a I take an input birthday string such as 02 26 1991 and make it into a Gregorian Calendar?

如何将输入的生日字符串(例如 02 26 1991)转换为公历?

I tried parsing it first but it keeps giving me an error message so I'm not quite sure what I'm doing wrong. I also have other input data before this date. One is another string and one is a double value.

我先尝试解析它,但它一直给我一条错误消息,所以我不太确定我做错了什么。在此日期之前,我还有其他输入数据。一个是另一个字符串,一个是双精度值。

采纳答案by cletus

Use SimpleDateFormatto parse the date and then assign it to a Calendar.

使用SimpleDateFormat解析日期,然后将其分配给Calendar

DateFormat df = new SimpleDateFormat("dd MM yyyy");
Date date = df.parse("02 26 1991");
Calendar cal = Calendar.getInstance();
cal.setTime(date);

The third line could be replaced with:

第三行可以替换为:

Calendar cal = new GregorianCalendar();

but I prefer the first version.

但我更喜欢第一个版本。

回答by objects

Use a DateFormat as shown here:

使用日期格式如图所示在这里

Example:

例子:

DateFormat dateFormat = new SimpleDateFormat("hh:mm dd/MM/yy");
dateFormat.setLenient(false);
Date d = dateFormat.parse("06:23 01/05/06");

Use the parse() method of the SimpleDateFormat class. You can use setLenient(false) to force strict parsing.

使用 SimpleDateFormat 类的 parse() 方法。您可以使用 setLenient(false) 强制严格解析。