Coxer
Coxer

Reputation: 1704

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?

Upvotes: 5

Views: 1980

Answers (2)

senia
senia

Reputation: 38045

+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

Upvotes: 8

Kevin Wright
Kevin Wright

Reputation: 49705

If you're looking for "correctness", then don't use SimpleDateFormat!

For one thing, it's not thread safe... and it's silently unsafe, you'll just end up with corrupt dates and no error being thrown. As you're using Scala then it's a fair bet that concurrent programming and thread safety will apply to you.

Use JodaTime, perhaps with one of the Scala wrappers. It gives you some far nicer tools for building date parsers, and generally does the right thing if you simply use the default parser without specifying any format string.

Upvotes: 3

Related Questions