jose920405
jose920405

Reputation: 8049

How to convert a string to a date, without losing the formatting

I have this date 2015-11-06T18:00:00-0500

My format is yyyy-MM-dd'T'HH:mm:ssZ

i try

let startDateString = "2015-11-06T18:00:00-0500"
let format = NSDateFormatter()
format.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

let startDateBtnEnd = format.dateFromString(startDateString)
println("startDateBtnEnd 2 \(startDateBtnEnd)")

But the log is startDateBtnEnd 2 Optional(2015-11-07 00:00:00 +0000)

Upvotes: 0

Views: 411

Answers (1)

Code Different
Code Different

Reputation: 93151

NSDate stores dates in UTC. You can convert it to the same moment in time in any timezone. But after losing too many neurons to mentally convert NSDate from one timezone to another, I decided to add my own extension to NSDate to print it out in the local timezone instead:

extension NSDate {
    func toString(timeZone: NSTimeZone = NSTimeZone.localTimeZone()) -> String {
        let formatter = NSDateFormatter()
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
        formatter.timeZone = timeZone

        return formatter.stringFromDate(self)
    }
}

// Usage:
print("startDateBtnEnd 2 \(startDateBtnEnd.toString())")

Upvotes: 1

Related Questions