私は通常、これでかなりうまくいきますが、NSDate
オブジェクトに問題があります。NSDate
明日の午前 8 時に (比較的) オブジェクト セットが必要です。これを行うにはどうすればよいですか?最も簡単な方法は何ですか?
3059 次
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 に答える