Reputation: 25
I am total Swift 2 newbie and got stuck with date formatting.
My system is set to "Swiss-German" and date format should be formatted like "25. Nov. 2015 19:25:56"
But playground's result sidebar shows "Nov 25, 2015, 7:25 PM": date formatted US style and AM/PM instead of 24 hrs format.
I tried
var myDate = NSDate()
print("date string:",myDate)
print(myDate.description) // no ouput
Output:
date string: 2015-11-25 18:21:58 +0000
2015-11-25 18:21:58 +0000
And
// How to check which locale Swift 2 is using?
I really would appreciate any help!
Thanks, Roland
Upvotes: 2
Views: 3291
Reputation: 86651
If you just print the date, it will do it in "debug" mode, no locale or timezone will be applied.
The proper way to get the date in the format you want is to use an NSDateFormatter. Then you can apply a time zone and a format or locale.
import Foundation
var myDate = NSDate()
print(myDate.description)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.localTimeZone()
formatter.dateFormat = "dd'.' MMM'.' yyyy HH':'mm':'ss"
print(formatter.stringFromDate(myDate))
The above prints
2015-11-26 11:55:55 +0000
26. Nov. 2015 11:55:55
I'm in the UK. If I set my PC to Central European Time, I get
2015-11-26 11:59:51 +0000
26. Nov. 2015 12:59:51
Upvotes: 0
Reputation: 17534
I don't know how to force Playground environment to use your locale, but you can do it in your own code.
import Foundation
print(NSDate())
print(NSDate().descriptionWithLocale(NSLocale(localeIdentifier: "zh_TW")))
print(NSDate().descriptionWithLocale(NSLocale(localeIdentifier: "de_DE")))
... output is ...
2015-11-25 19:24:53 +0000
2015年11月25日 星期三 中歐標準時間 下午8:24:53
Mittwoch, 25. November 2015 um 20:24:53 Mitteleuropäische Normalzeit
... check NSDateFormatter for more info
Upvotes: 1