xcode 比较目标 C 中的时间和日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7419381/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Comparing time and date in objective C
提问by kuchiyose
How do I compare in objective C to see if a certain time and date period overlaps another that is already in a plist for example?
例如,如何在目标 C 中进行比较以查看某个时间和日期期间是否与 plist 中已经存在的另一个重叠?
This is most commonly used in booking/reservation apps to see if that particular timeslot has been taken up etc.
这最常用于预订/预订应用程序中,以查看该特定时间段是否已被占用等。
回答by Ravi Chokshi
Try this to Compare ..
试试这个比较..
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM/dd/yyyy hh:mm:ss aa"];
NSDate *dateOne=[dateFormat dateFromString:@"01/09/2011 11:12:10 AM" ];
NSDate *dateTwo = [NSDate date];
switch ([dateOne compare:dateTwo]){
case NSOrderedAscending:
//NSLog(@"NSOrderedAscending");
break;
case NSOrderedSame:
//NSLog(@"NSOrderedSame");
{
break;
case NSOrderedDescending:
//NSLog(@"NSOrderedDescending");
break;
}
[dateFormat release];
回答by Youssef
Assuming you have the date stored as a NSDate, just use this:
假设您将日期存储为 NSDate,只需使用以下命令:
[myDate timeIntervalSinceNow];
That returns a NSTimeInterval which is just a float representing the time interval in seconds. If it is negative that means that the time that you are comparing is previous.
这将返回一个 NSTimeInterval,它只是一个浮点数,表示以秒为单位的时间间隔。如果它是负数,则意味着您正在比较的时间是以前的。
If your date is stored in the plist as a NSStringyou have to convert it to a NSDatefirst, use a NSDateFormatterfor that.
如果您的日期作为 a 存储在 plist 中,NSString您必须NSDate先将其转换为 a ,请使用 a NSDateFormatter。
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; //Change this to your date format
NSDate * date = [formatter dateFromString:yourString];
[formatter release];

