【发布时间】:2016-02-02 18:02:36
【问题描述】:
所以,我在这里寻找另一个问题,并提出这个问题:
我有一个NSDate 的扩展名
extension NSDate {
private class var formatter : NSDateFormatter {
let nsDateFormatter = NSDateFormatter()
nsDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
nsDateFormatter.locale = NSLocale.currentLocale()
return nsDateFormatter
}
//NSString to NSDate
public convenience init(dateString:String) {
let dateObj = NSDate.formatter.dateFromString(dateString)!
self.init(timeInterval: 0, sinceDate: dateObj)
}
//NSDate to String
public func getString() -> String {
return NSDate.formatter.stringFromDate(self)
}
}
这很好用:
var date = NSDate() //"Feb 2, 2016, 12:36 PM"
var string = date.getString() //"2016-02-02 12:36:11 -0500"
let copyDate = NSDate(dateString: string) //"Feb 2, 2016, 12:36 PM"
copyDate.getString() //"2016-02-02 12:36:11 -0500"
但是如果我使用,例如:
"EEE, d MMM YYYY HH:mm:ss zzz" 作为日期格式:
var date = NSDate() //"Feb 2, 2016, 12:58 PM"
var string = date.getString() //"Tue, 2 Feb 2016 12:58:48 GMT-5"
let copyDate = NSDate(dateString: string) //"Dec 22, 2015, 12:58 PM"
copyDate.getString() //"Tue, 22 Dec 2015 12:58:48 GMT-5"
为什么会这样?
它不应该与前一种情况相同吗?
为什么我现在有几天甚至一个月的时间中断?
【问题讨论】:
-
没有区别,我已经试过了。
-
@LeoDabus 我在我的 iMac 上,专门为此打开了一个操场,相信我,我已经尝试过了。
-
YYYY 大写字母是(在大多数情况下)不是你想要的,见例如stackoverflow.com/questions/15133549/….
-
问题从这行开始
let dateObj = NSDate.formatter.dateFromString(dateString)! -
@HugoAlonso stackoverflow.com/a/32023076/2303865
标签: ios swift swift2 nsdate nsdateformatter