Mike Pulsifer
Mike Pulsifer

Reputation: 279

Unable to parse a date

I'm getting a datetime string in the following format back from a web service:

2014-08-22T15:00:00-04:00

Originally, I manually stripped the pieces out and rebuilt it to an NSDate variable. The problem I ran into then was when I retrieved the day part of the date, hours 00 through 04 would give me the previous day. Even when applying the local timezone to the date formatter, the printed value of the new date ended with +0000, which can't be right.

Anyway, I then found some code on apple's site in Ojbective-C and translated it into Swift:

    func userVisibleDateTimeStringForRFC3339DateTimeString(rfc3339DateTimeString: String) -> NSDate {

        let rfc3339DateFormatter = NSDateFormatter()
        let enUSPOSIXLocale = NSLocale(localeIdentifier: "en_US_POSIX")
        rfc3339DateFormatter.locale = enUSPOSIXLocale
        rfc3339DateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
        let date = rfc3339DateFormatter.dateFromString(rfc3339DateTimeString)


        return date!
    }

(the original code produced a "user readable date string." I just needed the date.

Now, it crashes on the return statement because date is nil, meaning it's not parsing that datetime string.

I've even tried simply:

let format="yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"
var dateFmt = NSDateFormatter()

dateFmt.dateFormat = format

println(noaaDate)
let newreadableDate = dateFmt.dateFromString(noaaDate)
println(newreadableDate)

newreadableDate is nil

All I need is to convert that string into a date that will let me do proper day component comparisons later on.

Upvotes: 1

Views: 1706

Answers (1)

zaph
zaph

Reputation: 112855

Don't escape formatting characters, the 'Z' must not be escaped, it is a formatting syntax character. Only the 'T' must be escaped because it is a syntax character and should not be interpreted as one. The '-' and '=' are not syntax characters so they do not need to be escaped but can be.

From the docs: "ASCII letter from a to z and A to Z are reserved as syntax characters".
So any of the characters a-zA-Z are considered syntax characters unless they are escaped.

let format="yyyy-MM-dd'T'HH:mm:ssZ"

See: ICU Formatting Dates and Times

let noaaDate = "2014-08-22T15:00:00-04:00"
let format="yyyy-MM-dd'T'HH:mm:ssZ"

var dateFmt = NSDateFormatter()
dateFmt.dateFormat = format
let newreadableDate = dateFmt.dateFromString(noaaDate)
println(newreadableDate)

Output:

Optional(2014-08-22 19:00:00 +0000)

Upvotes: 2

Related Questions