iOS

ios相隔天数和是否为同一天

2017-02-20  本文已影响0人  ______空巷

首先,获得两个比较的日期

//创建时间格式

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *fromDate = [dateFormatter dateFromString:@"2017-01-09 12:02:03"];

NSDate *toDate = [NSDate date];

比较两个日期是否为同一天:

//判断是否为同一天

- (BOOL)isSameDay:(NSDate*)date1 date2:(NSDate*)date2

{

NSCalendar* calendar = [NSCalendar currentCalendar];

unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;

NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date1];

NSDateComponents* comp2 = [calendar components:unitFlags fromDate:date2];

return [comp1 day]  == [comp2 day] &&

[comp1 month] == [comp2 month] &&

[comp1 year]  == [comp2 year];

}

相隔多少天

//NSCalendarIdentifierGregorian 公历

NSCalendar *gregorian = [[NSCalendar alloc]

initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

//设定每周的第一天从星期几开始,比如:如需设定从星期日开始,则value传入1;如需设定从星期一开始,则value传入2

[gregorian setFirstWeekday:2];

NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];

if (labs(dayComponents.day) >= 1) {

//进行检测更新

}

关于NSDateComponents的讲解,可以查看https://my.oschina.net/yongbin45/blog/156181的介绍

上一篇下一篇

猜你喜欢

热点阅读