NSDate比今天更早

时间:2015-05-12 02:12:48

标签: ios objective-c nsdate

我理解如何比较两个if ([olderDate compare:[NSDate date]] == NSOrderedAscending) { // do something } 个对象,例如:

abstract class abstractClass
{
    public int x { get; private set; }
    public int y { get; private set; }

    protected abstractClass(int x) : this(x, defaultY) {}
    protected abstractClass(int x, int y)
    {
        this.x = x;
        this.y = y;
    }
}

class childClass : abstractClass
{
    childClass(int x)
        : base(x)
    {
    }
}

class childClass2 : abstractClass
{
    childClass(int x, int y)
        : base(x,y)
    {
    }
}

但是我想比较日期组件,而不是时间,因为在我的情况下,时间可以使比较不准确。

是否可以只比较日,月和年?

3 个答案:

答案 0 :(得分:4)

从iOS 8开始,NSCalendar有许多便捷方法可用于此类比较。

例如,有:

- (NSDate *)startOfDayForDate:(NSDate *)date NS_AVAILABLE(10_9, 8_0);

您可以从某个日期开始指定某一天(例如[NSDate date]表示“现在”),然后与之比较。

还有:

- (NSComparisonResult)compareDate:(NSDate *)date1 toDate:(NSDate *)date2 toUnitGranularity:(NSCalendarUnit)unit NS_AVAILABLE(10_9, 8_0);

您可以使用粒度NSCalendarUnitDay来调用它,直接进行所需的比较。

还有其他人。有关详细信息,请参阅NSCalendar.h,因为这些方法似乎不在类引用文档中。

答案 1 :(得分:2)

您可以通过这种方式获取日期组件

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:yourDate];

然后你可以比较

NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

答案 2 :(得分:0)

您可以使用此方法。

if ([olderDate timeIntervalSinceNow] > 0) {
  // do something
}
相关问题