/**
*? 將時間點轉(zhuǎn)化成日歷形式
*/
- (NSDate *)getCustomDateWithHour:(NSInteger)hour {
//獲取當(dāng)前時間
NSDate * destinationDateNow = [NSDate date];
NSCalendar *currentCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *currentComps = [[NSDateComponents alloc] init];
NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
currentComps = [currentCalendar components:unitFlags fromDate:destinationDateNow];
//設(shè)置當(dāng)前的時間點
NSDateComponents *resultComps = [[NSDateComponents alloc] init];
[resultComps setYear:[currentComps year]];
[resultComps setMonth:[currentComps month]];
[resultComps setDay:[currentComps day]];
[resultComps setHour:hour];
NSCalendar *resultCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
return [resultCalendar dateFromComponents:resultComps];
}
/**
*? 獲取時間段
*/
- (NSString *)getTheTimeBucket {
//? ? NSDate * currentDate = [self getNowDateFromatAnDate:[NSDate date]];
NSDate * currentDate = [NSDate date];
if ([currentDate compare:[self getCustomDateWithHour:0]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:9]] == NSOrderedAscending) {
return @"早上好";
} else if ([currentDate compare:[self getCustomDateWithHour:9]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:11]] == NSOrderedAscending) {
return @"上午好";
} else if ([currentDate compare:[self getCustomDateWithHour:11]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:13]] == NSOrderedAscending) {
return @"中午好";
} else if ([currentDate compare:[self getCustomDateWithHour:13]] == NSOrderedDescending && [currentDate compare:[self getCustomDateWithHour:18]] == NSOrderedAscending) {
return @"下午好";
} else {
return @"晚上好";
}
}
/**
*? [self getTheTimeBucket] 這樣就得到時間段了 擴展 通過[NSDate date]獲得的時間可能與當(dāng)前的系統(tǒng)時間不一樣,這是因為時區(qū)時差的緣故
*? 考慮時區(qū),獲取準(zhǔn)備的系統(tǒng)時間方法
*/
- (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate {
//設(shè)置源日期時區(qū)
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
//設(shè)置轉(zhuǎn)換后的目標(biāo)日期時區(qū)
NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
//得到源日期與世界標(biāo)準(zhǔn)時間的偏移量
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
//目標(biāo)日期與本地時區(qū)的偏移量
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
//得到時間偏移量的差值
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
//轉(zhuǎn)為現(xiàn)在時間
NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
return destinationDateNow;
}