一:NSDate
二:创建时间的方法
1.创建时间(类方法+)
(1):获取当前时间(0时区)
NSDate *beijingDate = [NSDate dateWithTimeInterval:intervalsinceDate:nowDate];
:SinceNow后是时间间隔。
>当前时间加上时间间隔,返回一个NSDate对象的时间
NSDate *date2 = [NSDate dateWithTimeIntervalSince1970:8];
(5):SinceReference的意思是:
>2001-01-01 00:00:00 +0000过了8秒
NSDate *date3 = [NSDate dateWithTimeIntervalSinceReferenceDate:8];
NSDate *date4 = [NSDatedistantFuture];
NSDate *date5 = [NSDatedistantPast];
NSTimeZone *zone = [NSTimeZonesystemTimeZone];
2.创建NSDate的初始化方法 (-)
>(上面的+号方法都有一个—号方法,alloc]init+相同的方法名)
NSDate *date6 = [date2addTimeInterval:8];
(2):用字符串转换成对象
//创建日期格式对象
NSDateFormatter *formatter = [[NSDateFormatteralloc]init];
//设置日期的格式
NSString *str1 =@"yyyy-MM-dd HH:mm:ss";
(3).用字符串转换成日期 (dateFromString)
//NSDateFormatter是设置日期格式的类
//然后可以帮助字符串NSString和NSDate的相互转化
/*
日期格式:
y:年 year
M:月 month(大写)
d:日 day
H:时(24进制) h(12进制)
m:分 minute;
s:秒 second
*/
//创建日期格式对象
NSDateFormatter *formatter = [[NSDateFormatteralloc] init];
//设置日期的格式
NSString *str1 =@"yyyy-MM-dd HH:mm:ss";
[formattersetDateFormat:str1];
NSDate *date8 = [formatterdateFromString:@"2015/10/9 11:50:40"];
(4).对应的日期转换成字符串(StringFromdate)
//在转转换成字符串时,自动的转换成当前时区的时间。
//但是原来的对象还是0时区的时间。
//2015-10-09 11:50:40
NSString *str = [formatterstringFromDate:date8];
三:NSDate对象持有的方法
1.时间间隔
// typedef double NSTimeInterval; NSTimeInterval实际上是double类型
//距离当前(0时区时间)时刻360秒的时间(NSDate当前时间)
NSDate *date1 = [NSDatedateWithTimeIntervalSinceNow:360];
NSLog(@"date1= %@",date1);
//获取当前系统时区
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSLog(@"zone = %@",zone);
//o时区和当前时区相差的时间:(NSTimeInterval获取时间间隔)
NSTimeInterval interval = [zone secondsFromGMT];
//昨天的现在时刻(60*60是一个小时,*24是一天的时间,然后减去,表示昨天的现在)
NSDate *date2 = [NSDatedateWithTimeIntervalSinceNow:-(60*60*24)];
NSLog(@"%@",date2);
//明年的这个时刻(假设今年是366天)
NSDate *date3 =[NSDatedateWithTimeIntervalSinceNow:366*24*60*60];
NSLog(@"%@",date3);
//计算给定Date对象和当前时间的时间间隔,时间单位为秒
//给定Date对象是date1(以date1的时间为基准,在它的时间的偏移)
NSTimeInterval time = [date1 timeIntervalSinceNow];
2.时间比较
NSDate *date4 = [NSDatedateWithTimeIntervalSince1970:0];
NSDate *date5 = [NSDatedateWithTimeInterval:0sinceDate:date4];
BOOL isEqual = [date5isEqualToDate:date4];
NSLog(@"%d",isEqual);