swift NSDateFormatter无法正常工作 [英] swift NSDateFormatter not working
问题描述
我正在尝试格式化时间如下:
I'm trying to format time as follows:
let formatter = NSDateFormatter()
formatter.dateFormat = "hh_mm_ss"
let d = formatter.stringFromDate(NSDate())
println("formatted text is: \(d)")
假设当前时间是2014年9月3日22:15:30
Suppose that current time is Sep 3, 2014 22:15:30
- 当我在操场上运行此脚本时,它打印正确格式化的时间:
22_15_30
。 - 在AppDelegate上运行时,它不打印格式化的时间:
22:15:30
- When I run this script on playground, it prints the time correctly formatted:
22_15_30
. - When running this on AppDelegate, it doesn't print the time formatted:
22:15:30
I我正在使用xcode 6 beta 5 ...我错过了什么吗?为什么stringFromDate没有返回格式化的正确日期?
I'm using xcode 6 beta 5... Am I missing something? Why stringFromDate doesn't return the correct date formatted?
编辑:我正在使用xcode 6 beta 6.
EDIT: I'm using xcode 6 beta 6.
谢谢!
推荐答案
24小时格式是HH,而不是hh 。
The 24-hour format is "HH", not "hh".
它在Playground 中工作的原因可能是
,用户定义的设置可以覆盖12/24格式的选择,比较
什么是处理NSDateFormatter语言环境的最佳方法是feechur?。
为安全起见,请为日期格式化程序设置en_US_POSIX区域设置:
The reason that it works in the Playground may be that user defined settings can override the 12/24-format choice, compare What is the best way to deal with the NSDateFormatter locale "feechur"?. To be on the safe side, set the "en_US_POSIX" locale for the date formatter:
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
// Swift 3:
formatter.locale = Locale(identifier: "en_US_POSIX")
这篇关于swift NSDateFormatter无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!