1

How to parse the following string to date

Mon Oct 22 03:00:26 +0000 2012

I tried MMM dd HH:mm:ss yyyy, but it is not working. I know I am missing something but couldn't find out that.

  String b="Mon Oct 22 03:00:26 +0000 2012";
  DateFormat a = new SimpleDateFormat("MMM dd HH:mm:ss yyyy");
  Date d=(Date)a.parse(b)
Brideau
  • 4,564
  • 4
  • 24
  • 33
Praveen
  • 77
  • 7
  • isn't this `DDD MMM dd HH:mm:ss zzz yyyy` format? – Hoh Feb 10 '14 at 00:23
  • This should not be marked as a duplicate. The presence of "+0000" in the middle of the string makes it different from the examples in the linked question it is "duplicating". Users unfamiliar with that code may try to use "ZZZZZ" to match that part of the string, which throws an error. – Brideau Dec 14 '17 at 16:48

2 Answers2

3

I'd recommend EEE MMM dd HH:mm:ss Z yyyy instead of HH:mm:ss yyyy.

Edit:

Specifically, your code would be:

String b="Mon Oct 22 03:00:26 +0000 2012";
  DateFormat a = new SimpleDateFormat("MMM dd HH:mm:ss Z yyyy");
  Date d=(Date)a.parse(b)

Edit after comment:

String b="Mon Oct 22 03:00:26 +0000 2012";
  DateFormat a = new SimpleDateFormat("MMM dd HH:mm:ss Z yyyy", Locale.getDefault());
  Date d=(Date)a.parse(b)
ViRALiC
  • 1,419
  • 4
  • 18
  • 46
  • When I parse in this format I get one hour extra. I mean instead of Mon Oct 22 00:00:12 BST 2012, I am getting Mon Oct 22 01:00:12 BST 2012, Why is that so? – Praveen Feb 10 '14 at 00:43
  • That is odd. It doesn't on my end. Try adding "Locale.getDefault()" to "a" as demonstrated in my answer. – ViRALiC Feb 10 '14 at 00:49
1

Try to do something like this:

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";        

try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    e.printStackTrace();
}

Ref: How to Convert String to Date in Java

OGHaza
  • 4,795
  • 7
  • 23
  • 29
kiki
  • 81
  • 9