如何确定NSDate(包括时间)是否已通过

时间:2021-09-12 20:51:50

How do I determine whether an NSDate (including time) has passed? I need to basically compare today's date to a date in the db but am stumped.

如何确定NSDate(包括时间)是否已通过?我需要基本上将今天的日期与数据库中的日期进行比较,但我很难过。

3 个解决方案

#1


89  

Try this:

尝试这个:

if ([someDate timeIntervalSinceNow] < 0.0) {
    // Date has passed
}

#2


6  

you need to use an NSDate comparison, many answers on here will assist you.

你需要使用NSDate比较,这里的许多答案都会对你有所帮助。

iOS: Compare two dates

iOS:比较两个日期

logic will need tweaking, but this should set you in the right direction:

逻辑将需要调整,但这应该让你朝着正确的方向:

- (BOOL)date:(NSDate*)date isBefore:(BOOL)before otherDate:(NSDate*)otherDate ;
{
    if(before && ([date compare:otherDate] == NSOrderedAscending))
        return YES;
    if (!before && ([date compare:otherDate] == NSOrderedDescending))
        return YES;  
}

usage:

用法:

if([self date:yourDate isBefore:YES otherDate:[NSDate date]]) 

#3


3  

You can use

您可以使用

[NSDate date];

to get an NSDate object representing the current time and date.

获取表示当前时间和日期的NSDate对象。

Then compare that to the date you are analysing, for example:

然后将其与您分析的日期进行比较,例如:

if ([currentDate timeIntervalSince1970] > [yourDate timeIntervalSince1970]) {
// yourDate is in the past
}

you can use this to compare any two dates. Hope this helps.

你可以用它来比较任何两个日期。希望这可以帮助。

#1


89  

Try this:

尝试这个:

if ([someDate timeIntervalSinceNow] < 0.0) {
    // Date has passed
}

#2


6  

you need to use an NSDate comparison, many answers on here will assist you.

你需要使用NSDate比较,这里的许多答案都会对你有所帮助。

iOS: Compare two dates

iOS:比较两个日期

logic will need tweaking, but this should set you in the right direction:

逻辑将需要调整,但这应该让你朝着正确的方向:

- (BOOL)date:(NSDate*)date isBefore:(BOOL)before otherDate:(NSDate*)otherDate ;
{
    if(before && ([date compare:otherDate] == NSOrderedAscending))
        return YES;
    if (!before && ([date compare:otherDate] == NSOrderedDescending))
        return YES;  
}

usage:

用法:

if([self date:yourDate isBefore:YES otherDate:[NSDate date]]) 

#3


3  

You can use

您可以使用

[NSDate date];

to get an NSDate object representing the current time and date.

获取表示当前时间和日期的NSDate对象。

Then compare that to the date you are analysing, for example:

然后将其与您分析的日期进行比较,例如:

if ([currentDate timeIntervalSince1970] > [yourDate timeIntervalSince1970]) {
// yourDate is in the past
}

you can use this to compare any two dates. Hope this helps.

你可以用它来比较任何两个日期。希望这可以帮助。