Java Parse Date w/ SimpleDateFormat

只谈情不闲聊 提交于 2019-12-14 04:01:06

问题


I'm sure this is a simple one! I've got this String String date = "Wed, 2 Jan 2013 12:17:15 +0000 (GMT)" which I want to parse to a Date to be able to set an JavaMail's sent date.

Here's my full code

String dateString = "Wed, 2 Jan 2013 12:17:15 +0000 (GMT)";
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
Date date = sdf.parse(dateString);
System.out.println("Date: " + date.toString());
email.setSentDate(oDate); // Assume email is initialised correctly

Expected output

Date: Wed, 2 Jan 2013 12:17:15 +0000 (GMT)

Actual output

Date: Wed Jan 02 12:17:15 GMT 2013

I'm not even bothered about the time component, as long as my email appears to be from the correct date.


回答1:


Try this:

String reformattedStr = sdf.format(sdf.parse(dateString));

or this

String reformattedStr = sdf.format(sdf.parse(date.toString()));



回答2:


Date.toString() applies its own format when converting to string:

Converts this Date object to a String of the form:

     dow mon dd hh:mm:ss zzz yyyy

You should use DateFormat to get a desired string, ie for a posted code example:

System.out.println(sdf.format(date));



回答3:


The setSentDate method will format the date properly for an email message before setting it in the email message. That's different than what Date.toString() does. See also the MailDateFormat class.



来源:https://stackoverflow.com/questions/16195459/java-parse-date-w-simpledateformat

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