问题
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