日期类的使用NSDate

日期类在需要记录时间的地方发挥着巨大的作用,也可以实时地获取程序使用的时间。配合 NSLocal ,NSDateFormatter 和 NSTimeZone 这几个类就可以涵盖所有的程序使用的时间日期的数据。

初始化一个 NSDate 类可以使用工厂方法和实例方法:

工厂方法

NSDate *time = [NSDate date]; //返回当前时间
NSDate *time = [NSDate dateWithTimeIntervalSinceNow:0.0]; //返回以当前时间为基准,然后过了secs秒的时间
NSDate *time = [NSDate dateWithTimeIntervalSince1970:100.0]; //返回以1970/01/01 GMT为基准,然后过了secs秒的时间
NSDate *time = [NSDate dateWithTimeIntervalSinceReferenceDate:100.0]; //返回以2001/01/01 GMT为基准,然后过了secs秒的时间
NSDate *time = [NSDate dateWithTimeInterval:100.0 sinceDate:time2]; //返回从某个时间之后过了多少秒
NSDate *time = [NSDate distantFuture];  //返回很多年以后的未来的某一天。
NSDate *time = [NSDate distantPast];    //返回很多年以前的某一天

实例方法

NSDate *time = [[NSDate alloc] init]; //返回当前时间
NSDate *time = [[NSDate alloc] initWithTimeInterval:1000.0 sinceDate:time2]; //返回从某个时间之后过了多少秒
NSDate *time = [[NSDate alloc] initWithTimeIntervalSince1970:1000000000.0]; //返回以1970/01/01 GMT为基准,然后过了secs秒的时间
NSDate *time = [[NSDate alloc] initWithTimeIntervalSinceNow:100.0]; //返回以当前时间为基准,然后过了secs秒的时间
NSDate *time = [[NSDate alloc] initWithTimeIntervalSinceReferenceDate:1000000.0]; //返回以2001/01/01 GMT为基准,然后过了secs秒的时间

日期间的比较 / 获取两个时间的间隔

NSLog(@"%d", [time isEqualToDate:time2]);  //是否相等
NSLog(@"%@", [time earlierDate:time2]);    //是否早于
NSLog(@"%@", [time2 laterDate:time]);      //是否低于
NSLog(@"%ld", [time2 compare:time]);       //排序时调用,返回 -1,0,1

NSLog(@"%f", [time timeIntervalSinceDate:time2]); //time2之后与time间的间隔
NSLog(@"%f", [time timeIntervalSince1970]);    //从1970年之后到time的间隔
NSLog(@"%F", [time timeIntervalSinceNow]);    //从现在到time之间的时间间隔
NSLog(@"%f", [time timeIntervalSinceReferenceDate]); //从以1970/01/01 GMT为基准到time的时间间隔

时间表示成字符串

- (NSString *)description; 以YYYY-MM-DD HH:MM:SS ±HHMM的格式表示时间。

NSLocale 的用法

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier"en_US"]; // 根据本地标识符创建本地化对象

[NSLocale availableLocaleIdentifiers]; // 获取系统所有本地化标识符数组列表  

[[NSLocale currentLocale] localeIdentifier]; //获取当前系统设置语言的标识符

[NSLocale lineDirectionForLanguage:[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]; //获取当前语言的排版方向和字符方向

[NSLocale preferredLanguages]; //获取用户的语言偏好设置列表 

[NSNotificationCenter defaultCenter] addObserver:self selector@selector(localChangedHandler)  name:NSCurrentLocaleDidChangeNotification object:nil];  // 监听用户本地化设置的消息

NSLocale *curLocal = [[NSLocale alloc]initWithLocaleIdentifier"zh-Hans"]; // 以本地化方式获取国际化信息的显示名称


// 设置固定的系统返回 语言数据
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh"];
NSDateFormatter *secondDateFormatter = [[NSDateFormatter alloc] init];
[secondDateFormatter setDateFormat:@"cccc"];  
secondDateFormatter.locale = locale;
NSDate *date = [NSDate date];
NSLog(@"%@", [secondDateFormatter stringFromDate:date]);