【问题标题】:how to get NSDate of a specific next day and time如何获取特定第二天和时间的 NSDate
【发布时间】:2016-08-01 08:34:25
【问题描述】:

我有一些事件需要计算NSDates。 例如,我试图在下周一上午 8:00 获得。 所以我尝试了一些东西,但没有任何效果:

1.

let nextMonday = NSCalendar.currentCalendar().dateBySettingUnit(NSCalendarUnit.Weekday, value: 2, ofDate: startDate, options: NSCalendarOptions.MatchNextTime)
let nextMondayEight = NSCalendar.currentCalendar().dateBySettingUnit(NSCalendarUnit.Hour, value: 8, ofDate: nextMonday!, options: NSCalendarOptions.MatchNextTime)

我明白了:

2016-04-12 05:00:00 +0000

那是星期二 8:00(时差是我的当地时间 GMT -3)。

2.

let unitFlags: NSCalendarUnit = [.Day, .Month, .Year]
let comp = NSCalendar.currentCalendar().components(unitFlags, fromDate: NSDate())
comp.timeZone = NSTimeZone.localTimeZone()
comp.weekday = 1
comp.hour = 8
comp.minute = 0
comp.second = 0
let compDate = NSCalendar.currentCalendar().dateFromComponents(comp)

print("time: \(compDate!)")

我明白了:

2016-04-11 05:00:00 +0000

那是今天 8:00,而不是下周一 8:00。


有什么建议吗? 谢谢

【问题讨论】:

标签: ios swift nsdate


【解决方案1】:

NSCalendar 有一个方法 nextDateAfterDate:matchingComponents:options 用于这种日期数学。

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()
components.hour = 8 // 8:00
components.weekday = 2 // Monday in Gregorian Calendar

let nextMondayEightOClock = calendar.nextDateAfterDate(NSDate(), matchingComponents: components, options: .MatchStrictly)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多