[iOS]時間篩選之<本週、上週、更早>
阿新 • • 發佈:2018-11-09
1、可以實現時間篩選,目測應該還有更簡單的方法。
思路: 獲取當天時間,和目標時間進行比對操作。
注意點:時區 時區 時區 重要的時區說三遍。
- (void)viewDidLoad { [super viewDidLoad]; NSDate * today = [NSDate date]; //定義當前時區時間 NSString * time [email protected]"2015-08-16 00:00:00"; NSDate* xmlData = [self dateFromString:time]; xmlData = [self getNowDateFromatAnDate:xmlData]; if([self intervalSinceNow:xmlData]>=[self getTodayisWeek:today]+7) { NSLog(@"這個日期是很早以前"); } if([self intervalSinceNow:xmlData]>=[self getTodayisWeek:today]&&[self intervalSinceNow:xmlData]<[self getTodayisWeek:today]+7) { NSLog(@"這個日期是上週"); } if([self intervalSinceNow:xmlData]<7&&[self intervalSinceNow:xmlData]<[self getTodayisWeek:today]) { NSLog(@"這個日期是本週"); } } - (int)intervalSinceNow: (NSDate *) theDate { NSTimeInterval late=[theDate timeIntervalSince1970]*1; NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0]; dat= [self getNowDateFromatAnDate:dat]; NSTimeInterval now=[dat timeIntervalSince1970]*1; NSString *
[email protected]""; NSTimeInterval cha=now-late; if (cha/86400>1) { timeString = [NSString stringWithFormat:@"%f", cha/86400]; timeString = [timeString substringToIndex:timeString.length-7]; return [timeString intValue]; } return -1; } - (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate { //設定源日期時區 NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT //設定轉換後的目標日期時區 NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone]; //得到源日期與世界標準時間的偏移量 NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate]; //目標日期與本地時區的偏移量 NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate]; //得到時間偏移量的差值 NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset; //轉為現在時間 NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate]; return destinationDateNow; } - (NSDate *)dateFromString:(NSString *)dateString{ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"]; NSDate *destDate= [dateFormatter dateFromString:dateString]; return destDate; } //獲得某日是周幾 -(int)getTodayisWeek:(NSDate *)today { today = [self getNowDateFromatAnDate:today]; NSCalendar*calendar = [NSCalendar currentCalendar]; NSDateComponents*comps; [comps setWeekday:0]; comps =[calendar components:(NSCalendarUnitWeekday)fromDate:today]; NSInteger weekday = [comps weekday]; // 星期幾(注意,週日是“1”,週一是“2”。。。。) int factWeekDay; //預設是週日開始 switch (weekday) { case 1: factWeekDay = 7 ; break; case 2: factWeekDay = 1 ; break; case 3: factWeekDay = 2 ; break; case 4: factWeekDay = 3 ; break; case 5: factWeekDay = 4 ; break; case 6: factWeekDay = 5 ; break; case 7: factWeekDay = 6 ; break; default: break; } return factWeekDay; }