iphone - 如何在 iPhone 中比较两个日期?

标签 iphone ios

我想设置当前日期和时间两天后的日期和时间。我如何使用 NSDate 和 dateformatter 设置它。我想要比较两天后的日期,之前是否设置过。

我现在为它编写代码, NSCalendar *日历 = [NSCalendar autoupdatingCurrentCalendar];

NSDate *pickerDate = [self.datePicker date];

NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                               fromDate:pickerDate];

NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) 
                                               fromDate:pickerDate];

NSDateComponents *dateComps = [[NSDateComponents alloc] init];

[dateComps setDay:[dateComponents day]];
[dateComps setMonth:[dateComponents month]];
[dateComps setYear:[dateComponents year]];
[dateComps setHour:[timeComponents hour]];
[dateComps setMinute:[timeComponents minute]];
[dateComps setSecond:00];

NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
appDelegate.setTimerByUser = [itemDate retain];

如何将其与当前时间和日期进行比较? 谢谢

最佳答案

查看 NSDate.h 并阅读 Apple 的文档,了解 NSDate 上的 -compare 函数。

例如,您可以这样做:

NSDate  *now = [NSDate date];
NSDate  *future = [now dateByAddingTimeInterval: 2 * 24 * 60 * 60]; // add two days

if ( [now compare: future] == NSOrderedAscending ) {
    // now is earlier than future so we will always get here
} else {
    // never reached but illustrates how you might use compare
}

关于iphone - 如何在 iPhone 中比较两个日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4363480/

相关文章:

iphone - testflight 会自动将新的 UDID 添加到我的 Apple 开发者帐户中吗

android - 将 ios 应用程序移植到 android

ios - 我的函数中的 NSJSONSerialization 返回错误

ios - systemSound 不再与使用 ARC 的升级版 Xcode 4.5.2 配合使用

iphone - 在 IOS 模拟器中访问摄像头

ios - 在 SFSafariViewController 上设置完成按钮颜色

iphone - isinf 被禁止提交到appstore

由于代码签名问题导致 iOS 测试飞行错误

ios - 在所有具有不同缩放比例/分辨率的 iPhone 中处理 UI

iphone - NSFetchRequest 内存问题