2013-03-07 19 views

回答

14

下面是如何WWDC 2011 session 117 - Performing Calendar Calculations教导我:

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,指出了。

+2

基于标签,这个问题似乎是为iOS。 'dateWithNaturalLanguageString:'方法仅适用于OSX,不适用于iOS。 – rmaddy 2013-03-07 03:02:53

+0

好吧,现在它增加了8个小时我认为,但在上午8点,它不会增加一天,它会回到今天。虽然在明天只有一个是明天...这是我的控制台日志的所有三个日期http://cl.ly/NPH5 – 2013-03-07 05:09:09

+0

而不是记录NSDate,你可以[使用NSDateFormatter来创建一个NSString]( http://i.stack.imgur.com/EXWgO.png)并记录下来? – 2013-03-07 12:19:34

1

雨燕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 
     } 

    } 
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 
} 
相关问题