< Objective-C >Foundation-NSDate

NSDate *date =[NSDate date];获取当前时间
(NSDate *)dateWithTimeIntervalSinceNow:(NSTimeInterval)根据某个时间间隔获取与当前时间(Now)间隔的新日期
(NSDate *)dateByAddingTimeInterval:(NSTimeInterval)根据某个时间间隔获取与实例保存时间间隔的新日期

NSDate *now = [NSDate date];
NSDate *tomorrow = [now dateByAddingTimeInterval:24*60*60];
NSDate *tomorrow2 = [NSDate dateWithTimeIntervalSinceNow:24*60*60];

日期比较

NSComparisonResult result = [now compare:tomorrow];
if(result == NSOrderedAscending) {
    NSLog(@"now<tomorrow");
}else if(result == NSOrderedDescending) {
    NSLog(@"now>tomorrow");
}else {
    NSLog(@"now=tomorrow");
}

获取时间间隔
-(NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;以refDate为基准时间,返回实例保存的时间与refDate的时间间隔
-(NSTimeInterval)timeIntervalSinceNow;以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔
-(NSTimeInterval)timeIntervalSince1970;以1970/01/01为基准时间,返回实例保存的时间与1970/01/01GMT的时间间隔

NSTimeInterval interval = [tomorrow timeIntervalSinceDate:now];
NSLog(@"%0.2lf",interval);

日期格式化(NSDateFormatter)

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy年MM月dd日 HH点mm分ss秒"];
NSString *dateString = [formatter stringFromDate:now];
NSLog(@"%@",dateString);
原文地址:https://www.cnblogs.com/aY-Wonder/p/4560660.html