Java string for utc date

This question is a duplicate of this question by intention. It seems that the eldest of them is “ignored”, while none of the answers is the answer.

I need to parse a given date with a given date pattern / format.

I have this code that should 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 get 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 happened to my date template? This seems like a mystery.

+4
source share
3 answers

The default language of your platform is apparently not English. Thu and Aug are English. You need to explicitly specify Locale as the 2nd argument in the SimpleDateFormat constructor :

 final SimpleDateFormat date_formatter = new SimpleDateFormat(date_format, Locale.ENGLISH); // <--- Look, with locale. 

Without it, the default platform locale is used instead to parse the day and month names. You can find out about the default Locale#getDefault() platform platform language Locale#getDefault() as follows:

 System.out.println(Locale.getDefault()); 
+11
source

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); } 
+1
source

I must specify the locale, for example:

 final SimpleDateFormat date_formatter = new SimpleDateFormat(date_format, Locale.ENGLISH); 

Thanks to BalusC with his excellent answer !

0
source

All Articles