While looking at this question, I discovered that both the OP's and the accepted answer's code, when run, produce a ParseException
. Here is the code:
String dateString = new java.util.Date().toString();
System.out.println(dateString);
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date date = format.parse(dateString);
System.out.println(date.toString());
After closely examining how the date string printed differs with the format provided, I still can't find why they don't match. Here is the date string printed:
Sat Aug 19 18:58:41 BST 2017
My instincts tell me that the reason why this does not work is that my locale is different - Locale.getDefualt()
returns ja_JP
.
The pattern does not matter, but the locale does.
Date#toString
usesLocale.US
and English names for days, months and time zones, whileSimpleDateFormat(String)
uses your default locale (specifically:Locale.getDefault(Locale.Category.FORMAT)
). If those two locales do not match, parsing may fail as the local names are not guaranteed to match.So you should be fine with
Excerpts from JDK 8:
SimpleDateFormat:
Date: