0

I am getting the current UTC NSDate and converting it to the timezone of the device. when it is converted to string, the output is correct and is according to the device timezone. But when I convert the string back to NSDate object, the output is again shown in UTC.

Here is the code I am trying

let date = NSDate.date()
let formatter: NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let timezone = NSTimeZone.systemTimeZone()
formatter.timeZone = timezone
let currentDate: String = formatter.stringFromDate(date)
let cd:NSDate = formatter.dateFromString(currentDate)!

I need to compare another date with the current date of user's device.

Any help will be highly appreciated. Thank you in advance.

Asbar
  • 391
  • 3
  • 14
  • What do you mean by "the output"? What output? As far as I'm aware, an `NSDate` doesn't *have* a time zone, so you shouldn't expect it to retain any information other than "a point in time". – Jon Skeet Oct 22 '14 at 12:22
  • when I log the currentDate I get 2014-10-22 17:03:16 but when I try to convert the currentDate string to NSDate and log 'cd' I get 2014-10-22 12:03:16 – Asbar Oct 22 '14 at 12:26
  • And that's presumably because that *is* the right UTC value, and logging `NSDate` just always logs the UTC value. If you want to log a value in a particular time zone, you should use an `NSDateFormatter` with that time zone set. – Jon Skeet Oct 22 '14 at 12:33
  • I am using NSDateFormatter and I am setting the timezone to the system timezone. as you can see in my code posted in the question. – Asbar Oct 22 '14 at 12:36
  • 1
    I mean *when logging*. You're using an `NSDateFormatter` to come up with `cd`, but you haven't shown how you're *logging* `cd`. You should log it by formatting `cd` using an appropriate formatter. – Jon Skeet Oct 22 '14 at 12:39
  • Thank you for clearing it to me. Kindly post it as an answer so that I can accept it. – Asbar Oct 22 '14 at 12:53

0 Answers0