如何从Swift中的NSDate获取日,月和小时

时间:2016-08-05 10:05:55

标签: swift nsdate nsdatecomponents

我有一个名为reservationDate的NSDate对象,我想从日期中获取日,月和小时。但是,我得到了错误的价值观。我怎样才能得到这些值?

reservationDate对象的值 reservationDate NSDate 2016-08-05 21:00:00 UTC 因此,我希望每天得到5分,每小时21分,但是我每天收到6分钟,每小时收到0分钟。我应该期待别的吗?

let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: reservationDate)
let day = components.day
let hour = components.hour

3 个答案:

答案 0 :(得分:1)

尝试使用Calendar

UTC对象设置时区
let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let calendar = NSCalendar.currentCalendar()
calendar.timeZone = NSTimeZone(name: "UTC")!
let components = calendar.components(unitFlags, fromDate: NSDate())
let day = components.day
let hour = components.hour

答案 1 :(得分:1)

您尚未设置时区。请指定“UTC”。

NSCalendar.currentCalendar().timeZone = NSTimeZone(name: "UTC")!

答案 2 :(得分:0)

let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
var convertedDate = dateFormatter.stringFromDate(currentDate)
dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy, HH:mm"
convertedDate = dateFormatter.stringFromDate(currentDate)