我通常对此非常满意,但我遇到了NSDate
对象的问题。我需要明天早上8点(相对)设置一个NSDate
对象。我该怎么做?什么是最简单的方法?
答案 0 :(得分: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,指出了这一点。
答案 1 :(得分: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
}
}
答案 2 :(得分:0)
Swift 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
}