francojay
francojay

Reputation: 510

Why is NSDate different inside of a string?

In playground, I am testing some code.

If I type in

NSDate() 

then I get "Nov 28, 2014, 7:56 PM"

But, if I type in

var dateString: String = "\(NSDate())"

then I get "2014-11-29 01:56:45 +0000"

Why is the default time different within a string than a simple NSDate() declaration?

Upvotes: 0

Views: 59

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236458

In playground, I am testing some code.

If I type in

NSDate() then I get "Nov 28, 2014, 7:56 PM"

this is your local time but you can't store timezone into a NSDate object.

But, if I type in

var dateString: String = "(NSDate())" then I get "2014-11-29 01:56:45 +0000"

this is Greenwich Mean Time which and thats how it is stored into your NSDate

let dateString = "\(Date())"

is the same as:

let dateString = Date().description

if you would like to know the localtime of a Date you can do as follow:

edit/update Swift 3 or later:

extension Formatter {
    static let localTimestamp: DateFormatter = {
        let dateFormatter = DateFormatter()
        dateFormatter.timeStyle = .full
        return dateFormatter
    }()
}
extension Date {
    var localTimestamp: String {
        return Formatter.localTimestamp.string(from: self)
    }
}

Date().localTimestamp  // "6:40:19 PM Brasilia Standard Time"

Upvotes: 1

Related Questions