0

I have encountered with below lines of code sometimes doesn't return proper UTC value:

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
formatter.timeZone = NSTimeZone(abbreviation: "UTC")

Returns:

"2016-12-11 2:07:35 am +0000"

Instead of:

"2016-12-11 02:07:35 +0000"

What's wrong with that?

iamburak
  • 3,508
  • 4
  • 34
  • 65
  • 1
    Set the date formatter locale to POSIX, compare e.g. http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformatter-locale-feature or http://stackoverflow.com/questions/40692378/swift-3-dateformatter-doesnt-return-date-for-hhmmss. – Martin R Dec 11 '16 at 10:07
  • @MartinR Thanks I added that posix. What you think using currentLocale() here's an answer below. I think It is not proper, isn't it? – iamburak Dec 11 '16 at 11:04

1 Answers1

-2

please use these code

    let date = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    formatter.timeZone = NSTimeZone.localTimeZone()
    formatter.locale = NSLocale.currentLocale()
    print(formatter.stringFromDate(date))
  • I think using currentLocale() is not proper thing with UTC, I added posix as "en_US_POSIX" for my above code like Martin said in above comment. – iamburak Dec 11 '16 at 11:01
  • A date formatter uses the current locale and the local time zone by default. – Martin R Dec 11 '16 at 11:06