NSDate
在OC中,Foundation框架为我们提供了强大的时间操作类’NSDate’,该类封装了各种处理时间和日期的API
1.构造一个’NSDate’类
//获取系统当前时间
NSDate *date1 = [NSDate date];
NSLog(@"date = %@",date1);
//当前系统时间+100秒
NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:100];
NSLog(@"date2 = %@",date2);
//
NSDate *date3 = [NSDate dateWithTimeIntervalSince1970:100];
NSLog(@"date3 = %@",date3);
//
NSDate *date4 = [NSDate dateWithTimeInterval:100 sinceDate:[NSDate date]];
NSLog(@"date4 = %@",date4);
2.关于’时间戳’
//将一个日期转换成时间戳,此时间戳是以1970为标准
NSTimeInterval timeInterval1970 = [[NSDate date] timeIntervalSince1970];
NSLog(@"timeInterval = %f",timeInterval1970);
NSTimeInterval timeIntervalNow = [[NSDate date] timeIntervalSinceNow];
NSLog(@"timeIntervalNow = %f",timeIntervalNow);
3.将’NSDate’转化成’NSString’
//如何将NSDate转换成NSString
NSDateFormatter *dateFormatter = [NSDateFormatter new];
//设置时区(默认时区)
dateFormatter.timeZone = [NSTimeZone systemTimeZone];
//设置时间输出格式
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ms"];
NSString *string = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@",string);
4.将’NSString’转换成’NSDate’
//将时间的类型的字符串转化成日期
NSString *string1 = @"1999-01-01 15:30:23";
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormatter dateFromString:string1];
NSLog(@"%@",[dateFormatter dateFromString:string1]);
NSTimeInterval timeInterval = date.timeIntervalSinceNow;
NSLog(@"距今现在已经%f",timeInterval);
int m = -timeInterval /60 ;
NSLog(@"%d分钟",m);