【问题标题】:Compare current date and time iOS比较当前日期和时间 iOS
【发布时间】:2016-08-05 22:58:09
【问题描述】:
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                         [dateFormatter setDateFormat:@"hh:mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate* firstDate = [dateFormatter dateFromString:resultString];
NSDate* secondDate = [dateFormatter dateFromString:@"16:00"];
NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];

if (timeDifference < 0){

我正在尝试检索当前时间并将其与输入时间进行比较。这是我现在代码的一部分(iOS 的目标 c),但 NSTimeInterval 会导致断点。除此之外,我还想将日期纳入比较中,因此如果在星期二下午 5:00 之后发生事件。因此,如果您对如何合并它有任何想法,将不胜感激!

【问题讨论】:

  • 约翰下面的回答是比较日期的基本形式。 (请注意,在比较之前无需转换为字符串并再次返回。)关于“周二下午 5 点之后”的那一行有点偷偷摸摸,可能需要一个单独的问题——需要指定不同时区的行为,无论是“任何”星期二等

标签: ios objective-c datetime


【解决方案1】:

比较两个日期:

if ([firstDate compare:secondDate] == NSOrderedDescending) {
    NSLog(@"firstDate is later than secondDate");
    NSTimeInterval timeDifference = [firstDate timeIntervalSinceDate:secondDate];
} else if ([firstDate compare:secondDate] == NSOrderedAscending) {
    NSLog(@"firstDate is earlier than secondDate");
    NSTimeInterval timeDifference = [secondDate timeIntervalSinceDate:firstDate];
} else {
    NSLog(@"firstDate and secondDate are the same");
}

这应该可以解决您的问题。

【讨论】:

  • 如果我希望它只适用于某一天怎么办?假设如果在周二的 5:00 发生事件,但在周三的 5:00 不会发生。
  • @DSmith:像这样的 NSDate 对象所体现的“日期”在绝对全局意义上表示现实世界时间中的特定单点。该时间点可以呈现为某个时区的日期和时间,或与其他特定时间点进行比较。它确实表示一般的“时间”或任何其他一般概念。如果您想弄清楚如何表示您正在寻找的内容,您可能需要更具体地提出该问题以获得最佳建模帮助。
【解决方案2】:
NSDate *currentTime = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                         [dateFormatter setDateFormat:@"hh:mm"];
NSString *resultString = [dateFormatter stringFromDate: currentTime];
NSDate* firstDate = [dateFormatter dateFromString:resultString];
NSDate* secondDate = [dateFormatter dateFromString:@"16:00"];
 NSComparisonResult result = [secondDate compare:firstDate];
        switch(result){
            case NSOrderedDescending:
                NSLog(@"date1 is later than date2");
                break;
            case NSOrderedAscending:
                NSLog(@"date1 is earlier than date2");
                break;
            default:
                NSLog(@"dates are the same");
                break;
         }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 2017-10-12
    • 2011-11-14
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 2015-07-20
    相关资源
    最近更新 更多