如何让 NSDate() 打印当前本地时间
How to make NSDate() print the current local time
我已经在操场上试过了(我在评论中展示了打印的内容):
extension NSDate {
static func currentDate() -> NSDate {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.localTimeZone()
calendar.locale = NSLocale.currentLocale()
let components = calendar.components([.Year, .Month, .Day], fromDate: NSDate())
components.hour = 00
components.minute = 00
components.second = 00
return calendar.dateFromComponents(components)! // "Dec 29, 2015, 12:00 AM"
}
}
print(NSDate.currentDate()) // "2015-12-28 22:00:00 +0000
有人知道这里发生了什么吗?
我只想要当前日期 (year/month/day)。我进行此扩展是因为 NSDate()
有问题,它关闭了 2 小时(显示上午 11 点 24 分,而不是下午 1 点 24 分)
Swift 中的 NSDate()
和 Objective-C 中的 [NSDate date]
都保存 UTC 日期。你不能改变它的行为。
但是,您可以创建格式化程序并转换为所需的语言环境和日期格式,并将日期存储为字符串值。
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*your desired format*/
let date = dateFormatter.dateFromString(/*your date string*/)
我已经在操场上试过了(我在评论中展示了打印的内容):
extension NSDate {
static func currentDate() -> NSDate {
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone.localTimeZone()
calendar.locale = NSLocale.currentLocale()
let components = calendar.components([.Year, .Month, .Day], fromDate: NSDate())
components.hour = 00
components.minute = 00
components.second = 00
return calendar.dateFromComponents(components)! // "Dec 29, 2015, 12:00 AM"
}
}
print(NSDate.currentDate()) // "2015-12-28 22:00:00 +0000
有人知道这里发生了什么吗?
我只想要当前日期 (year/month/day)。我进行此扩展是因为 NSDate()
有问题,它关闭了 2 小时(显示上午 11 点 24 分,而不是下午 1 点 24 分)
Swift 中的 NSDate()
和 Objective-C 中的 [NSDate date]
都保存 UTC 日期。你不能改变它的行为。
但是,您可以创建格式化程序并转换为所需的语言环境和日期格式,并将日期存储为字符串值。
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = /*your desired format*/
let date = dateFormatter.dateFromString(/*your date string*/)