1.NSDate
在OC中 Foundation框架为我们提供了强大的时间操作类’NSDate ’ , 该类封装了各种处理时间和日期的API
获取系统当前时间(系统时间为格林尼治时间GMT 与北京时间相差8小时 北京时间=CMT+8)
NSDate *date1=[NSDate date];
NSLog(@"%@",date1);
TimeInterval 是以秒为单位的时间片 也叫时间戳
1.[NSDate dateWithTimeIntervalSinceNow:120]//以现在时间为基准,120s之后的时间(-的为之前,+的为之后)
2.[NSDate dateWithTimeIntervalSince1970:100]//1970.01.01为基准,100s之后的时间
3.[NSDate dateWithTimeInterval:120 sinceDate:[NSDate date]]//现在时间为基准 120s之后的时间
返回的类型都是NSDate
通过时间追加创建NSDate
NSDate *date2=[date1 dateByAddingTimeInterval:120];
2.日期的比较 NSTimeInterval
时间差:(timeIntervalSinceDate)
NSDate *dateNow=[NSDate date];//当前时间
NSDate dateHourAgo=[dateNow datebyAddingTimeInterval:-3600];//一小时之前
NSTimeInterval timeBetween=[dateNow timeIntervalSinceDate:dateHourAgo];//两者时间差
NSLog(@"%f",timeBetween);
日期早晚比较
1.BOOL flag= [dateNow isEqualToDate:dateHourAgo];
if (flag) {
NSLog(@"dateNow dateHourAgo");
}//两个日期是否相等
2.NSDate *date6= [dateNow earlierDate:dateHourAgo];//与dateHourAgo比较返回较早的日期
3.NSDate *date7= [date6 laterDate:dateHourAgo];//与dateHourAgo比较返回较晚的日期
4.compare你叫大小
NSComparisonResult result= [dateNow compare:dateHourAgo];
switch (result) {
case NSOrderedDescending:{
NSLog(@"dateNow > dateHourAgo");
}
break;
case NSOrderedAscending:{
NSLog(@"dateNow < dateHourAgo");
}
break;
case NSOrderedSame:{
NSLog(@"dateNow = dateHourAgo");
}
break;
}
3.NSCalendar和NSDateComponents创建日期更加直观
4.时区(NSTimeZone)
5.字符串与NSDate之间的转换(NSDateFormatter)
1.将NSDate转换成字符串
NSDateFormatter *dateFormatter=[NSDateFormatter new];
//设置时区(默认时区)
dateFormatter.timeZone=[NSTimeZone defaultTimeZone];//defaultTimeZone默认本地时区
//设置时间输出格式
//[dateFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSLog(@"%@",string1);
2.将字符串转换成NSDate
NSString *string2=@"1970-01-01 08:00:00";
[ dateFormatter setTimeZone:[NSTimeZone
timeZoneWithAbbreviation:@"UTC"]];//UTC世界统一标准时间
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date9=[dateFormatter dateFromString:string2];
NSLog(@"%@",date9);