NSDate,比较两个日期 [英] NSDate, comparing two dates
问题描述
好的,我已经在这几天工作了,而且我被卡住了。我想要做的是将当前时间与预定时间进行比较。我想要发生的是,每天在特定时间我想要触发某些代码,但不是在我指定的时间之前。
Ok, I have been working on this for a couple of days now and am stuck. What I am trying to do is compare the current time with a predetermined time. What I want to happen is, Everyday at certain times I want certain code to fire, but not before the time of day that I specify.
所以,基本上如果当前时间等于或等于预定时间然后触发此代码。或者触发这行代码。
so, basically if the "current time" is the same or equal to "predetermined time" then fire this code. Or fire this line of code.
听起来很简单,但是我在抓两次比较时遇到了麻烦。
Sounds simple, but I am having trouble grabbing comparing the two times.
我已将字符串格式化为类似日期
I have formatted a string to a date like so
NSString* dateString = @"11:05 PM";
NSDateFormatter* firstDateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[firstDateFormatter setDateFormat:@"h:mm a"];
[firstDateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate* date = [firstDateFormatter dateFromString:dateString];
NSLog(@"date %@",date);
然后我就这样抓住当前时间
then i grab the current time like so
NSDate *currentTime = [NSDate dateWithTimeIntervalSinceNow:[[NSTimeZone localTimeZone] secondsFromGMT]];
NSDateComponents* comps = [[NSCalendar currentCalendar]
components: NSHourCalendarUnit |NSMinuteCalendarUnit
|NSSecondCalendarUnit fromDate:currentTime];
[[NSCalendar currentCalendar] dateFromComponents:comps];
那我该怎么比较这两次呢?我已经尝试了我能想到的一切,请帮助。
SO how do I compare these two times? I have tried everything I can think of, please help.
推荐答案
你可以尝试以下代码行吗?
Can you try below lines of code?
switch ([dateOne compare:dateTwo]){
case NSOrderedAscending:
NSLog(@"NSOrderedAscending");
break;
case NSOrderedSame:
NSLog(@"NSOrderedSame");
break;
case NSOrderedDescending:
NSLog(@"NSOrderedDescending");
break;
}
但在您的情况下,我认为您需要将两个日期保持为相同的格式。 。或者像这样的东西
But in your case I think you need to keep both dates in same format ..or some thing like this
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
[components setHour:23];//change your time to 24hrs formate
[components setMinute:05];
[components setSecond:00];
NSDate *dateOne = [[NSCalendar currentCalendar] dateFromComponents:components];
components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSDate *dateTwo = [[NSCalendar currentCalendar] dateFromComponents:components];
并在dateOne和dateTwo之间进行比较。
and do comparison between dateOne and dateTwo.
这篇关于NSDate,比较两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!