【问题标题】:how to compare two dates and time, EXP: 07/10/2015 12:30 to 08/10/2015 02:00 in ios?如何比较两个日期和时间,EXP:ios 中的 07/10/2015 12:30 到 08/10/2015 02:00?
【发布时间】:2015-10-07 10:07:41
【问题描述】:
 NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];

[timeFormatter setDateStyle:NSDateFormatterNoStyle];

[timeFormatter setTimeZone:[NSTimeZone localTimeZone]];

[timeFormatter setDateFormat:@"dd/MM/YYYY HH:mm"];

NSDate *startDate = [timeFormatter1 dateFromString:@"07/10/2015 12:30"];

NSDate *EndDate = [timeFormatter1 dateFromString:@"08/10/2015 02:30"];


if([startDate compare:EndDate] == NSOrderedAscending)

    return YES;

 else

    return NO;

我正在关注上面的代码,但每次输出都是错误的结果(去“return No”)。

同时 EXP:07/10/2015 12:30 到 07/10/2015 23:30 这工作正常。

我需要同时使用两种格式。

请帮帮我?

【问题讨论】:

  • 我认为你错了timeFormatter1。可能你错过了timeFormatter。并且在 startDate 和 EndDate 中为零。

标签: ios objective-c date time compare


【解决方案1】:

问题在于年份格式。使用“yyyy”而不是“YYYY”来解决问题。

这里是工作代码:

NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];

    [timeFormatter setDateStyle:NSDateFormatterNoStyle];

    [timeFormatter setTimeZone:[NSTimeZone localTimeZone]];

    [timeFormatter setDateFormat:@"dd/MM/yyyy HH:mm"];

    NSDate *startDate = [timeFormatter dateFromString:@"07/10/2015 12:30"];

    NSDate *EndDate = [timeFormatter dateFromString:@"08/10/2015 02:30"];


    if([startDate compare:EndDate] == NSOrderedAscending)

        NSLog(@"Ascending");

    else

        NSLog(@"Descending");

http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns

查看此链接了解更多日期格式

【讨论】:

    【解决方案2】:

    根据Apple Documentation的NSDate比较:

    返回一个 NSComparisonResult 值,该值指示接收者的时间顺序和另一个给定日期。

    - (NSComparisonResult)compare:(NSDate *)anotherDate
    

    参数 anotherDate

    与接收者进行比较的日期。该值不能为零。如果值为 nil,则行为未定义,并且可能会在 Mac OS X 的未来版本中发生变化。

    返回值

    如果:

    receiver 和 anotherDate 完全相等,NSOrderedSame

    接收者在时间上比另一个日期晚,NSOrderedDescending

    接收者在时间上早于另一个日期,NSOrderedAscending 换句话说:

    if ([date1 compare:date2] == NSOrderedSame) ...
    

    请注意,在您的特定情况下,阅读和编​​写此内容可能更容易:

    if ([date2 isEqualToDate:date2]) ...
    

    Apple Documentation about this one

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2016-12-16
      相关资源
      最近更新 更多