Reputation: 521
I am trying to convert a string to proper date format using Java's SimpleDateFormat
. For some reason, it's not working with certain months like "Mar", "May", "Oct", and "Dec." Can somebody help me? It works fine for all other months.
import java.sql.Date;
import java.text.SimpleDateFormat;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
public class test {
public static void main(String args[]) throws java.text.ParseException {
try {
SimpleDateFormat parse = new SimpleDateFormat("dd. MMM yyyy hh:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//why this doesn't work with certain months like Mar, May, Oct, and Dec? otherwise it works fine
String dateTime = "01. Jun 2010 15:30:32";
//String dateTime = "07. Mar 2011 15:20:10";
//String dateTime = "07. May 2011 15:20:10";
//String dateTime = "07. Oct 2011 15:20:10";
//String dateTime = "07. Dec 2011 15:20:10";
java.util.Date parsed =parse.parse(dateTime);
System.out.println("formatted: " + formatter.format(parsed));
} catch(ParseException e) {
System.out.println("Caught " + e);
}
}
}
Upvotes: 2
Views: 5005
Reputation: 1109635
You need to set the locale on SimpleDateFormat
, otherwise the platform default locale will be used for month names. You can do that by passing it as 2nd argument to the SimpleDateFormat
constructor. If you want to work with English formatted month names, pass Locale.ENGLISH
.
new SimpleDateFormat("dd. MMM yyyy hh:mm:ss", Locale.ENGLISH);
By the way, you can learn about your platform default locale by
System.out.println(Locale.getDefault());
This is configureable at OS level (in Windows control panel, for example) and as JVM argument.
Upvotes: 4