I have a string in the form MMM/dd/yyyy, ie. May/21/2010. Now I want to convert it to yyyyMMdd, ie. 20100521.
My code is:
public static void main(String[
SimpleDateFormat uses your locale - so your computer is probably set to use Danish by default. Specify the English Locale explicitly:
DateFormat formatter = new SimpleDateFormat("MMM", Locale.ENGLISH);
Use SimpleDateFormat(String pattern, Locale locale) to add Locale
to your date parsing (for english, use Locale.ENGLISH
).
Better solution:
public String transformPrevDate(String datoe) {
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMdd");
try {
return dateFormat2.format(dateFormat.parse(datoe));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Your transformDate
method can be much simpler written like this:
DateFormat input = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
DateFormat output = new SimpleDateFormat("yyyyMMdd");
public String transformPrevDate(String datoe) throws ParseException {
return output.format(input.parse(datoe));
}
You don't need to do your parsing yourself.
use SimpleDateFormat(String pattern, Locale locale)
;
You will need to apply the locale on SimpleDateFormat.
Here's a more shorter version:-
public String transformPrevDate(String date) {
DateFormat oldFormat = new SimpleDateFormat("MMM/dd/yyyy", Locale.ENGLISH);
DateFormat newFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
String formattedDate = "";
try {
formattedDate = newFormat.format(oldFormat.parse(date));
}
catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
@Test
public void testTransformPrevDate() {
assertEquals("20110113", transformPrevDate("Jan/13/2011"));
assertEquals("20010203", transformPrevDate("Feb/03/2001"));
}
SimpleDateFormat
is locale-dependent, and it's using your own locale by default. If you would like to use an English-based locale, you can create it by passing in a Locale when you create your SimpleDateFormat.
So to use a US-based locale, change your SimpleDateFormat
initialization to:
DateFormat formatter = new SimpleDateFormat("MMM", Locale.US);
DateFormat formatter2 = new SimpleDateFormat("MM", Locale.US);