如何检查一个日期是否为“明天”?
我不想像给今天的日期添加小时或其他内容一样,因为如果今天已经是22:59
,加太多会导致到第二天,而如果时间是12:00
,加太少会错过明天。
如何检查两个NSDate
并确保其中一个等同于另一个的明天?
如何检查一个日期是否为“明天”?
我不想像给今天的日期添加小时或其他内容一样,因为如果今天已经是22:59
,加太多会导致到第二天,而如果时间是12:00
,加太少会错过明天。
如何检查两个NSDate
并确保其中一个等同于另一个的明天?
使用NSDateComponents
,您可以从代表今天的日期中提取日、月和年份组件,忽略小时、分钟和秒钟组件,加上一天,并重新构建对应于明天的日期。
因此,假设您想要将当前日期(包括保持与“现在”日期相同的小时、分钟和秒钟信息)增加一天,您可以使用dateWithTimeIntervalSinceNow
添加24 * 60 * 60秒的时间间隔到“现在”,但更好的方法(且适用于DST等情况)是使用NSDateComponents
:
NSDateComponents* deltaComps = [[[NSDateComponents alloc] init] autorelease];
[deltaComps setDay:1];
NSDate* tomorrow = [[NSCalendar currentCalendar] dateByAddingComponents:deltaComps toDate:[NSDate date] options:0];
但是如果你想生成明天午夜的日期,你可以直接获取当前日期的月份/日期/年份组成部分,不包括小时/分钟/秒数,然后加上1天,再重新构建一个日期:
// Decompose the date corresponding to "now" into Year+Month+Day components
NSUInteger units = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
NSDateComponents *comps = [[NSCalendar currentCalendar] components:units fromDate:[NSDate date]];
// Add one day
comps.day = comps.day + 1; // no worries: even if it is the end of the month it will wrap to the next month, see doc
// Recompose a new date, without any time information (so this will be at midnight)
NSDate *tomorrowMidnight = [[NSCalendar currentCalendar] dateFromComponents:comps];
附注:您可以在日期和时间编程指南中阅读关于日期概念的真正有用的建议和内容,特别是这里关于日期组件的部分。
NSCalendar
的 dateFromComponents
返回 nullable
结果的问题?我知道明天一定存在,并希望在编码时利用这个事实。然而,在 Swift 中使用这种方法时,tomorrowMidnight
可能是 nil
,至少编译器是这样认为的。 - i4niaciOS 8中NSCalendar
有一个方便的方法叫做isDateInTomorrow
。
Objective-C
NSDate *date;
BOOL isTomorrow = [[NSCalendar currentCalendar] isDateInTomorrow:date];
Swift 3
let date: Date
let isTomorrow = Calendar.current.isDateInTomorrow(date)
Swift 2
let date: NSDate
let isTomorrow = NSCalendar.currentCalendar().isDateInTomorrow(date)
NSCalendar
/Calendar
来创建明天:extension Calendar {
var tomorrow: Date? {
return date(byAdding: .day, value: 1, to: startOfDay(for: Date()))
}
}