美文网首页
时间的各种操作

时间的各种操作

作者: 木马不在转 | 来源:发表于2016-08-24 18:25 被阅读7次

由NSDate转换为NSString:

SDateFormatter*dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString*strDate = [dateFormatter stringFromDate:[NSDate date]];

由NSString转换为NSDate:

NSDateFormatter*dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *date =[dateFormatter dateFromString:@"2010-08-04 16:01:03"];

比较2个时间段的间隔

NSCalendar *cal = [NSCalendar currentCalendar];

unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;

NSDateComponents *components = [cal components:unitFlags fromDate:[self.formatter dateFromString:sendString] toDate:[self.formatter dateFromString:endSreing] options:0];

日期之间比较可用以下方法

-(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

相关文章

网友评论

      本文标题:时间的各种操作

      本文链接:https://www.haomeiwen.com/subject/mfsosttx.html