objectivec日期和时间

我们使用NSDate类比较日期,并计算两个日期之间的日期和时间间隔:

可以用当前的日期和时间创建一个NSDate:

NSDate *myDate = [NSDate date];

可以创建一个NSDate,表示从现在开始的24小时:

    NSTimeInterval secondsPerDay = 4*60*60;
    NSDate *tomorrow = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];

可以使用如下代码,根据一个已有的日期创建一个日期:

    NSTimeInterval secondsPerDay = 4*60*60;  
    NSDate *yesterday = [[NSDate date] addTimeInterval:secondsPerDay];

可以比较两个日期是否完全相等:

BOOL sameDate = [date1 isEqualToDate:date2]; 

判断一个日期是在另一个日期之前还是之后,使用如下代码:

   - (BOOL)isEqualToDate:(NSDate *)otherDate;

      与otherDate比较,相同返回YES

 

    - (NSDate *)earlierDate:(NSDate *)anotherDate;

      与anotherDate比较,返回较早的那个日期

 

    - (NSDate *)laterDate:(NSDate *)anotherDate;

      与anotherDate比较,返回较晚的那个日期

 

    - (NSComparisonResult)compare:(NSDate *)other;

      该方法用于排序时调用:

      当实例保存的日期值与anotherDate相同时返回NSOrderedSame

      当实例保存的日期值晚于anotherDate时返回NSOrderedDescending

      当实例保存的日期值早于anotherDate时返回NSOrderedAscending

 

计算两个日期之间相隔多少秒:

  NSTimeInterval secondsBetweenDates =  [date2 timeIntervalSinceDate: date1]; 

计算现在和将来的一个日期之间相隔多少秒:

NSTimeInterval secondsUntilTomorrow  = [tomorrow timeIntervalSinceNow]; 

 

原文地址:https://www.cnblogs.com/appwgh/p/2517431.html