This question is a duplicate of this question by intention. It seems like the older one is "ignored", while none of the answers there is the answer.
I need to parse a given date with a given date pattern/format.
I have this code, which is supposed to work:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main
{
public static void main(String[] args)
{
final Date date = string_to_date("EEE MMM dd HH:mm:ss zzz yyyy",
"Thu Aug 14 16:45:37 UTC 2011");
System.out.println(date);
}
private static Date string_to_date(final String date_format,
final String textual_date)
{
Date ret = null;
final SimpleDateFormat date_formatter = new SimpleDateFormat(
date_format);
try
{
ret = date_formatter.parse(textual_date);
}
catch (ParseException e)
{
e.printStackTrace();
}
return ret;
}
}
For some reason I'm getting this output:
java.text.ParseException: Unparseable date: "Thu Aug 14 16:45:37 UTC 2011"
at java.text.DateFormat.parse(DateFormat.java:337)
at Main.string_to_date(Main.java:24)
at Main.main(Main.java:10)
null
What's wrong with my date pattern? This seems to be a mystery.
Your platform default locale is apparently not English. Thu
and Aug
are English. You need to explicitly specify the Locale
as 2nd argument in the constructor of SimpleDateFormat
:
final SimpleDateFormat date_formatter =
new SimpleDateFormat(date_format, Locale.ENGLISH); // <--- Look, with locale.
Without it, the platform default locale will be used instead to parse day/month names. You can learn about your platform default locale by Locale#getDefault()
the following way:
System.out.println(Locale.getDefault());
This should parse the given string.
public static void main(String[] args) throws ParseException
{
String sd = "Thu Aug 14 16:45:37 UTC 2011";
String dp = "EEE MMM dd HH:mm:ss zzz yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dp);
Date d = sdf.parse(sd);
System.out.println(d);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With