OC基础 NSDate
#import <Foundation/Foundation.h> int main(int argc, const char * argv[])
{ @autoreleasepool { NSDate *date = [NSDate date];
NSLog(@"date = %@",date); //距离现在时间多少s之后的时间
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:];
NSLog(@"date2 = %@",date2); //时间戳:距离1970/01/01 00:00:00之后的秒数
//距离1970/01/01 这个时间点100s之后的时间
NSDate *date3 = [NSDate dateWithTimeIntervalSince1970:];
NSLog(@"date3 = %@",date3); //距离date3之后100s的时间
NSDate *date4 = [NSDate dateWithTimeInterval: sinceDate:date3];
NSLog(@"date4 = %@",date4); //遥远的未来
NSDate *date5 = [NSDate distantFuture];
NSLog(@"date5 = %@",date5); //遥远的过去
NSDate *date6 = [NSDate distantPast];
NSLog(@"date6 = %@",date6); NSDate *date7 = [NSDate date];
//返回以当前时间为基准,然后过了1000秒的时间
NSDate *date8 = [NSDate dateWithTimeIntervalSinceNow:];
//以date7为基准时间,返回实例保存的时间与date7的时间间隔
double time = [date8 timeIntervalSinceDate:date7];
NSLog(@"time = %f",time);
//返回以当前NSDate对象为基准,偏移1000秒后得到的新NSDate对象
NSDate *date9 = [date8 dateByAddingTimeInterval:];
NSLog(@"date7--date9 = %@--%@",date7,date9); //与date9比较,返回较早的那个日期
NSDate *date10 = [date7 earlierDate:date9];
//与date9比较,返回较晚的那个日期
NSDate *date11 = [date7 laterDate:date9];
NSLog(@"date10--date11 = %@--%@",date10,date11); NSDate *dateNow = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
//设置格式
df.dateFormat = @"yyyy-MM-dd HH:mm:ss";
//NSDate转NSString
NSString *dateTime = [df stringFromDate:dateNow];
NSLog(@"dateTime = %@",dateTime); NSString *dateStr = @"2015-03-10 00:00:00";
//NSString转NSDate
NSDate *date12 = [df dateFromString:dateStr];
NSLog(@"date12 = %@",date12);
}
return ;
}
测试结果: