iOS日历:获取昨天, 一周前的今天 ,两周前的今天 ,上个月最后一天
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:[[NSDate alloc] init]];
[components setHour:- [components hour]];
[components setMinute:- [components minute]];
[components setSecond:- [components second]];
//今天
NSDate *today = [cal dateByAddingComponents:components toDate:[[NSDate alloc] init] options:0];
//昨天
[components setHour:-24];
[components setMinute:0];
[components setSecond:0];
NSDate *yesterDay = [cal dateByAddingComponents:components toDate:today options:0];
//一周前
components = [cal components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[[NSDate alloc] init]];
[components setDay:([components day] - ([components weekday] - 1))];
NSDate *thisWeek = [cal dateFromComponents:components];
//两周前
[components setDay:([components day] - 7)];
NSDate *lastWeek = [cal dateFromComponents:components];
//上个月最后一天
[components setDay:([components day] - ([components day] -1))];
NSDate *thisMonth = [cal dateFromComponents:components];
//两个月前最后一天
[components setMonth:([components month] - 1)];
NSDate *lastMonth = [cal dateFromComponents:components];
NSLog(@"today=%@",today);//today=2015-10-21 16:00:00 +0000**
NSLog(@"yesterday=%@",yesterDay);//yesterday=2015-10-20 16:00:00 +0000**
NSLog(@"thisWeek=%@",thisWeek);//thisWeek=2015-10-15 16:00:00 +0000**
NSLog(@"lastWeek=%@",lastWeek);//lastWeek=2015-10-08 16:00:00 +0000**
NSLog(@"thisMonth=%@",thisMonth);//thisMonth=2015-09-30 16:00:00 +0000**
NSLog(@"lastMonth=%@",lastMonth);//2015-08-31 16:00:00 +0000**
iOS 13位(毫秒)时间戳输出
NSString *timeStr =@"2015-10-20 16:00:00 +0000";
NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:[timeStr doubleValue]/1000];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSString *string = [dateFormatter stringFromDate:d];
_label_time.text = string;