20

如何检查日期是否天生就是明天?

我不想为今天这样的日期添加小时或任何内容,因为如果今天已经是22:59,添加太多会转到后天,如果时间添加太少12:00会错过明天。

我怎样才能检查两个NSDates 并确保一个相当于明天的另一个?

4

3 回答 3

52

使用NSDateComponents您可以从代表今天的日期中提取日/月/年分量,忽略小时/分钟/秒分量,添加一天,并重建对应于明天的日期。

因此,假设您想在当前日期准确地添加一天(包括保持小时/分钟/秒信息与“现在”日期相同),您可以将 24*60*60 秒的 timeInterval 添加到“现在”使用dateWithTimeIntervalSinceNow,但最好(和 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];

PS:您可以在Date and Time Programming Guide中阅读有关日期概念的非常有用的建议和内容,尤其是这里有关日期组件的内容。

于 2012-10-01T22:31:16.780 回答
7

在 iOS 8 中有一个方便的方法NSCalendar调用isDateInTomorrow.

Objective-C

NSDate *date;
BOOL isTomorrow = [[NSCalendar currentCalendar] isDateInTomorrow:date];

斯威夫特 3

let date: Date
let isTomorrow = Calendar.current.isDateInTomorrow(date)

斯威夫特 2

let date: NSDate
let isTomorrow = NSCalendar.currentCalendar().isDateInTomorrow(date)
于 2016-03-30T18:47:14.120 回答
1

您也许可以利用NSCalendar/Calendar创造明天:

extension Calendar {
    var tomorrow: Date? {
        return date(byAdding: .day, value: 1, to: startOfDay(for: Date()))
    }
}
于 2018-11-12T19:46:32.017 回答