前言:服务器返回的一般是时间戳,转成所需要的日期要注意时区,通过格林日历可以准确的获取当前的时间
1、当前的格林日历定义宏:
#define CURRENT_CALENDAR [NSCalendar currentCalendar]
2、NSCalendarUnit类型封装成宏:
#define DATE_COMPONENTS (NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit)
3、比较是否今天
- (BOOL)isTheSameDate: (NSDate *) aDate
{
NSDateComponents *components1 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:self];
NSDateComponents *components2 = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:aDate];
return ((components1.year == components2.year) &&
(components1.month == components2.month) &&
(components1.day == components2.day));
}
4、根据服务器返回的时间搓计算出当前的格林日历
// 返回当前的格林日历
- (NSDateComponents*)componentsWithDate:(NSDate*)date{
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//获取星期
NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *cmp = [gregorian components:unitFlags fromDate:date];
return cmp;
}
// 调用次接口的结果.year:年 ,结果.month:月,结果.day:天、等等
网友评论