2

我通常对此很满意,但我在处理这个NSDate对象时遇到了麻烦。我需要NSDate为明天早上 8 点(相对)设置一个对象。我将如何做到这一点,最简单的方法是什么?

4

3 回答 3

15

以下是WWDC 2011 会议 117 - 执行日历计算教我的方法:

NSDate* now = [NSDate date] ;

NSDateComponents* tomorrowComponents = [NSDateComponents new] ;
tomorrowComponents.day = 1 ;
NSCalendar* calendar = [NSCalendar currentCalendar] ;
NSDate* tomorrow = [calendar dateByAddingComponents:tomorrowComponents toDate:now options:0] ;

NSDateComponents* tomorrowAt8AMComponents = [calendar components:(NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:tomorrow] ;
tomorrowAt8AMComponents.hour = 8 ;
NSDate* tomorrowAt8AM = [calendar dateFromComponents:tomorrowAt8AMComponents] ;

可惜iOS没有[NSDate dateWithNaturalLanguageString:@"tomorrow at 8:00 am"]。谢谢rmaddy指出这一点。

于 2013-03-07T02:37:15.983 回答
1

Swift 2.1中:

    let now = NSDate()
    let tomorrowComponents = NSDateComponents()
    tomorrowComponents.day = 1

    let calendar = NSCalendar.currentCalendar()
    if let tomorrow = calendar.dateByAddingComponents(tomorrowComponents, toDate: now, options: NSCalendarOptions.MatchFirst) {

        let flags: NSCalendarUnit = [.Era, .Year, .Month, .Day]
        let tomorrowValidTime: NSDateComponents = calendar.components(flags, fromDate: tomorrow)
        tomorrowValidTime.hour = 7

        if let tomorrowMorning = calendar.dateFromComponents(tomorrowValidTime) {
            return tomorrowMorning
        }

    }
于 2016-05-08T13:25:01.923 回答
0

斯威夫特 3+

private func tomorrowMorning() -> Date? {
    let now = Date()
    var tomorrowComponents = DateComponents()
    tomorrowComponents.day = 1
    let calendar = Calendar.current
    if let tomorrow = calendar.date(byAdding: tomorrowComponents, to: now) {
        let components: Set<Calendar.Component> = [.era, .year, .month, .day]
        var tomorrowValidTime = calendar.dateComponents(components, from: tomorrow)
        tomorrowValidTime.hour = 7
        if let tomorrowMorning = calendar.date(from: tomorrowValidTime)  {
            return tomorrowMorning
        }

    }
    return nil
}
于 2016-10-10T10:04:27.273 回答