Parse a string in Date in Java

I am trying to parse a string to a date, this is what I have:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zZ (zzzz)"); Date date = new Date(); try { date = sdf.parse(time); } catch (ParseException e) { e.printStackTrace(); } 

parsing line:

 Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time) 

I followed http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Pretty sure I did everything from the book. But that gives me a ParseException .

 java.text.ParseException: Unparseable date: "Sun Jul 15 2012 12:22:00 GMT+0300 (FLE Daylight Time)" 

What am I doing wrong? The templates I tried:

 EEE MMM dd yyyy HH:mm:ss zzz EEE MMM dd yyyy HH:mm:ss zZ (zzzz) 
+6
source share
4 answers

You seem to be mixing patterns for z and z . If you ignore (FLE Daylight Time) , since this is the same information as in GMT+0300 , the problem becomes that SimpleDateFormat wants either GMT +0300 or GMT+03:00 . The latter option can be analyzed as follows:

 String time = "Sun Jul 15 2012 12:22:00 GMT+03:00 (FLE Daylight Time)"; SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zzz"); Date date = sdf.parse(time); 

[EDIT]
In light of other messages about the operation of their timelines, this is probably due to the fact that your timeline contains conflicting information or mixed formats.

+11
source

Try it like this.

 System.out.println(new SimpleDateFormat( "EEE MMM dd yyyy HH:mm:ss zZ (zzzz)").format(new Date())); 

Conclusion:

 Thu Jul 12 2012 12:41:35 IST+0530 (India Standard Time) 
+1
source

You can try to print a date format string:

 /** * @param args */ public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd yyyy HH:mm:ss zZ (zzzz)"); Date date = new Date(); try { // System.out.println(sdf.format(date)); date = sdf.parse(time); } catch (Exception e) { e.printStackTrace(); } } 
+1
source

If you have problems with locales, you can set the default locale for the entire application

 Locale.setDefault(Locale.ENGLISH); 

or just use english on SimpleDateFormat

 SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH); 

You can also use Locale.US or Locale.UK .

+1
source

Source: https://habr.com/ru/post/920293/


All Articles