Convert a string to a GregorianCalendar

*爱你&永不变心* 提交于 2019-11-26 09:58:19

问题


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

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.


回答1:


Use SimpleDateFormat to parse the date and then assign it to a 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.




回答2:


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.



来源:https://stackoverflow.com/questions/2331513/convert-a-string-to-a-gregoriancalendar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!