8

I want to parse a date with timezone from a string in the format "31-12-2014 18:09 +05:30". I tried to parse using simple-Date-Format using "d-MM-yyyy HH:mm ZZ" and "d-MM-yyyy HH:mm Z". But it is giving me a un-parables date exception. How to do this? Please help me.

AkshayP
  • 2,083
  • 2
  • 16
  • 26
Sumodh S
  • 697
  • 1
  • 14
  • 34

4 Answers4

10
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm XXX");
Date d = sdf.parse("31-12-2014 18:09 +05:30");
System.out.println(d);

Note that you can't use X before SimpleDateFormat of JDK7, because it's the ISO 8601 time zone format.

With Java 6 you can only use ZZZ but it won't match +05:30 because Z match RFC 822 time zone format

If you're using Java 6, please refer to this answer : Converting ISO 8601-compliant String to java.util.Date

Community
  • 1
  • 1
alain.janinm
  • 19,595
  • 10
  • 61
  • 107
  • How to parse `Wed May 23 16:52:42 EDT 2018` date? When I put simple date format as `ddd MMM dd HH:mm:ss XXX yyyy` it gives `java.text.ParseException: Unparseable date: "Wed May 23 16:52:42 EDT 2018"` error and when I try `ddd MMM dd HH:mm:ss EDT yyyy` it says illegal character T which does make sense.. – Aalap Patel May 28 '18 at 14:46
  • @AalapPatel Please read the Date and Time Patterns in the documentation referenced in my answer to understand how it works. If you still have issue you can ask a specific question if there is not already one giving you the answer in StackOverflow. – alain.janinm May 29 '18 at 07:14
3

use X instead of Z or ZZ as below:

String str = "31-12-2014 18:09 +05:30";
DateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm X");
System.out.println(format.parse(str));
Output:
Wed Dec 31 18:39:00 IST 2014
SMA
  • 35,277
  • 7
  • 46
  • 71
  • How to parse `Wed May 23 16:52:42 EDT 2018` date? When I put simple date format as `ddd MMM dd HH:mm:ss XXX yyyy` it gives `java.text.ParseException: Unparseable date: "Wed May 23 16:52:42 EDT 2018"` error and when I try `ddd MMM dd HH:mm:ss EDT yyyy` it says illegal character T which does make sense.. So what is the correct way to recognize EDT in the format ? Thanks in advance... – Aalap Patel May 28 '18 at 14:56
1

You have two errors: first, you should use two ds for the day. Second, use X instead of Z for the timezone. X represents the format that you are using. See the docs for more info. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

"dd-MM-yyyy HH:mm X"
forgivenson
  • 4,323
  • 2
  • 17
  • 28
1

Others have pointed out the X option in Java SE 7. If you, however, have an older Java version, then you can change the timezone part to +0530, then it will work with Z (which is availabe even in Java SE 1.4).

meskobalazs
  • 15,136
  • 2
  • 35
  • 58