iOS開發 判斷日期是今天,昨天還是明天
阿新 • • 發佈:2019-02-19
- (NSString*)weekdayStringFromDate:(NSString*)featureDate { <span style="color:#33cc00;">// 建立 格式 物件</span> NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; <span style="color:#33cc00;"> // 設定 日期 格式 可以根據自己的需求 隨時調整, 否則計算的結果可能為 nil</span> formatter.dateFormat = @"yyyy-MM-dd HH-mm-ss"; <span style="color:#33cc00;">// 將字串日期 轉換為 NSDate 型別</span> NSDate *inputDate = [formatter dateFromString:featureDate]; <span style="color:#33cc00;">// 生成今天日期時間</span> NSTimeInterval secondsPerDay = 24 * 60 * 60; NSDate *today = [[NSDate alloc] init]; NSDate *tomorrow, *yesterday; tomorrow = [today dateByAddingTimeInterval: secondsPerDay]; yesterday = [today dateByAddingTimeInterval: -secondsPerDay]; <span style="color:#33cc00;">// 10 first characters of description is the calendar date:</span> NSString * todayString = [[today description] substringToIndex:10]; NSString * yesterdayString = [[yesterday description] substringToIndex:10]; <span style="color:#33cc00;">//根據返回日期判斷是否是今天還是昨天</span> NSString * dateString = [[inputDate description] substringToIndex:10]; if ([dateString isEqualToString:todayString]) { return @"今天"; } else if ([dateString isEqualToString:yesterdayString]) { return @"昨天"; } <span style="color:#33cc00;"> //剩下的返回星期幾就行了</span> NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"週日", @"週一", @"週二", @"週三", @"週四", @"週五", @"週六", nil]; NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"]; [calendar setTimeZone: timeZone]; NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit; NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate]; return [weekdays objectAtIndex:theComponents.weekday]; }