1.首先獲取當(dāng)前時(shí)間的字符串
+ (NSString *)getCurrentTime{
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
[formatter setTimeZone:timeZone];
NSString *dateTime=[formatter stringFromDate:[NSDate date]];
return dateTime;
}
2.將指定的時(shí)間戳按相同的格式(例如:yyyy-MM-dd HH:mm:ss),轉(zhuǎn)化為字符串
3.將當(dāng)前時(shí)間oneDay與指定時(shí)間anotherDay進(jìn)行對(duì)比
①如果result == NSOrderedDescending瘸恼,說(shuō)明當(dāng)前時(shí)間大于指定時(shí)間
②如果result == NSOrderedAscending劣挫,說(shuō)明當(dāng)前時(shí)間小于指定時(shí)間
③如果以上兩種都不是,說(shuō)明當(dāng)前時(shí)間與指定時(shí)間相同
+ (int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateA = [dateFormatter dateFromString:oneDay];
NSDate *dateB = [dateFormatter dateFromString:anotherDay];
NSComparisonResult result = [dateA compare:dateB];
if (result == NSOrderedDescending) {
//NSLog(@"DateA is in the future");
return 1;
}
else if (result == NSOrderedAscending){
//NSLog(@"DateA is in the past");
return -1;
}else{
//NSLog(@"Both dates are the same");
return 0;
}
}