NSDate的使用比较简单,梳理了一下,主要是以下几类:
1、NSDate的创建
通过类方法:
NSDate * date1 = [NSDate date];
NSDate * date2 = [NSDate dateWithTimeIntervalSinceNow:NSTimeIntervalSince1970];
其他类方法:dateWithTimeInterval:sinceDate:、dateWithTimeIntervalSinceReferenceDate:、dateWithTimeIntervalSince1970:
通过实例方法,不再赘述了,与类方法基本一一对应。
2、获取可以表示的最远的未来时间和最早时间
[NSDate distantFuture]、[NSDate distantPast],主要与定时器结合使用。
3、时间的比较
- (BOOL)isEqualToDate:(NSDate *)otherDate;
与otherDate比较,相同返回YES
- (NSDate *)earlierDate:(NSDate *)anotherDate;
与anotherDate比较,返回较早的那个日期
- (NSDate *)laterDate:(NSDate *)anotherDate;
与anotherDate比较,返回较晚的那个日期
- (NSComparisonResult)compare:(NSDate *)other;
该方法用于排序时调用:
. 当实例保存的日期值与anotherDate相同时返回NSOrderedSame
. 当实例保存的日期值晚于anotherDate时返回NSOrderedDescending
. 当实例保存的日期值早于anotherDate时返回NSOrderedAscending
4、获取时间间隔
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;
以refDate为基准时间,返回实例保存的时间与refDate的时间间隔
- (NSTimeInterval)timeIntervalSinceNow;
以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔
- (NSTimeInterval)timeIntervalSince1970;
以1970/01/01 GMT为基准时间,返回实例保存的时间与1970/01/01 GMT的时间间隔
- (NSTimeInterval)timeIntervalSinceReferenceDate;
以2001/01/01 GMT为基准时间,返回实例保存的时间与2001/01/01 GMT的时间间隔
+ (NSTimeInterval)timeIntervalSinceReferenceDate;
以2001/01/01 GMT为基准时间,返回当前时间(Now)与2001/01/01 GMT的时间间隔
5、将时间表示成字符串
- (NSString *)description;
以YYYY-MM-DD HH:MM:SS ±HHMM的格式表示时间。
其中 "±HHMM" 表示与GMT的存在多少小时多少分钟的时区差异。比如,若时区设置在北京,则 "±HHMM" 显示为 "+0800"
6、常量
NSTimeIntervalSince1970
表示自1970年1月1日至2001年1月1日的时间间隔。