swift NSDateFormatter无法正常工作 [英] swift NSDateFormatter not working

查看:196
本文介绍了swift NSDateFormatter无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化时间如下:

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


  1. 当我在操场上运行此脚本时,它打印正确格式化的时间: 22_15_30

  2. 在AppDelegate上运行时,它不打印格式化的时间: 22:15:30

  1. When I run this script on playground, it prints the time correctly formatted: 22_15_30.
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆