Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java parsing date with timezone from a string

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.

like image 845
Sumodh S Avatar asked Dec 31 '14 12:12

Sumodh S


People also ask

Can we get timezone from date Java?

DateFormat getTimeZone() Method in Java with ExamplesThe getTimeZone() method in DateFormat class is used to return the current time-zone of the calendar of this DateFormat. Parameters: The method does not take any parameters. Return Value: The method returns timezone associated with the calendar of DateFormat.

How do you show timezone in formatted date in Java?

You can display timezone easily in Java using SimpleDateFormat(“z”).


1 Answers

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

like image 192
alain.janinm Avatar answered Oct 03 '22 06:10

alain.janinm