Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a date with timezone correctly?

I'm trying to convert a string of text into a date with the following code:

//Input String
str = "14/01/26,12:13:13+00"

//Format
format = new java.text.SimpleDateFormat("yy/MM/dd,HH:mm:ssz")

//Conversion
format.parse(str)

But I obtain the following:

Exception: Unparseable date: "14/01/26,12:13:13+00"

How does my format have to be changed in order to parse this date correctly?

like image 349
Coxer Avatar asked Jan 26 '14 12:01

Coxer


People also ask

How do you parse the date with the time zone?

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);

How do you read a timestamp with time zones?

To calculate UTC time one has to subtract the offset from the local time, e.g. for "15:00−03:30" do 15:00 − (−03:30) to get 18:30 UTC. Show activity on this post. That timestamp has a timezone offset that is telling you what time it was and the UTC offset. With no offset it becomes 2017-02-03T14:16:59.094-00:00 .

What is UTC timestamp format?

Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.

How do you format a timestamp?

With the fractional part included, the format for these values is ' YYYY-MM-DD hh:mm:ss [. fraction ]' , the range for DATETIME values is '1000-01-01 00:00:00.000000' to '9999-12-31 23:59:59.999999' , and the range for TIMESTAMP values is '1970-01-01 00:00:01.000000' to '2038-01-19 03:14:07.999999' .


1 Answers

+00 is invalid time zone. It should be +0000.

You could add 00 to str and replace z with Z in pattern to use RFC 822 time zone format:

new java.text.SimpleDateFormat("yy/MM/dd,HH:mm:ssZ").parse(str + "00")
// java.util.Date = Sun Jan 26 16:13:13 MSK 2014

java.util.Date (and java.text.SimpleDateFormat) is not the best choice for project. See this answer for some details.

As a bonus DateTimeFormat from Joda-Time allows you to parse your str without modifications:

// I'm using the same pattern with `Z` here
DateTimeFormat.forPattern("yy/MM/dd,HH:mm:ssZ").parseDateTime(str)
// org.joda.time.DateTime = 2014-01-26T16:13:13.000+04:00
like image 101
senia Avatar answered Oct 06 '22 00:10

senia