使用NSDate获取1天

时间:2014-08-01 08:32:17

标签: objective-c ios7 nsdate nsdateformatter

如何使用NSDate获得1天,即从 2014-08-01 00:00:00 +0000 2014-08-01 23:59:59 +0000 < / strong>即可。使用NSDate可以获得这个吗?

1 个答案:

答案 0 :(得分:0)

我不清楚你的问题。如果您希望第二天获得NSDate

+ (NSDate *)numberOfDays:(NSInteger)numberOfDays from:(NSDate *)fromDate {
    NSDateComponents *dayComponent = [[NSDateComponents alloc] init];
    dayComponent.day = numberOfDays;

    NSCalendar *calendar = [NSCalendar currentCalendar];
    return [calendar dateByAddingComponents:dayComponent toDate:fromDate options:0];
}

如果你想比较两个NSDate是否在同一天,那么(来自NSDate类别):

- (BOOL)isOnTheSameDayAs:(NSDate *)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components1 = [calendar components:(NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit) fromDate:self];
    NSDateComponents *components2 = [calendar components:NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit |  NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit fromDate:date];

    return ((components1.year == components2.year) &&
            (components1.month == components2.month) &&
            (components1.day == components2.day));
}