日期操作
时间:2017年8月14日 周一
时间戳
NSString *str = @"1983-04-17";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.dateFormat = @"yyyy-MM-dd";
NSDate *date = [df dateFromString:str];
NSTimeInterval dd = [date timeIntervalSinceNow];//时间戳一直是负数
NSTimeInterval ss = [date timeIntervalSince1970];//时间大于1970是正数,否则负数
NSDate *dds = [NSDate dateWithTimeIntervalSinceNow:dd];
NSDate *sss = [NSDate dateWithTimeIntervalSince1970:ss];
dds跟sss是相同日期
1、比较日期大小
默认会比较到秒,要记得设置日期格式
- (void)action {
NSString *str = @"1990-04-17";
NSDateFormatter *df = [[NSDateFormatter alloc]init];
df.dateFormat = @"yyyy-MM-dd";
NSDate *date = [df dateFromString:str];
NSComparisonResult result =[date compare:[NSDate date]];
}
NSComparisonResult:
NSOrderedAscending ,升序, [A compare:B];,就像AB顺序一样,B更大,所以就是上升了;
NSOrderedSame, 相同
NSOrderedDescending:降序,A大于B
2、计算年龄:
//计算年龄
- (double )calculateAge:(NSString *)str {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *birthDay = [dateFormatter dateFromString:str];
//获取时间戳,时间戳是负数
NSTimeInterval time = [birthDay timeIntervalSinceNow];
double year = floor(ABS(time)/(3600.0 * 24 * 365)); //3600秒 * 24小时*365天
return year;
}
3、计算时间差
用这个函数
- (NSTimeInterval)timeIntervalSinceDate:(NSDate *)anotherDate;
- (void )calculateMargin:(NSString *)str {
str = @"2018-08-14";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd";
NSDate *birthDay = [dateFormatter dateFromString:str];
//现在的时间
NSDate * nowDate = [NSDate date];
//计算两个中间差值(秒),nowDate大于birthDay,time为正数
NSTimeInterval time = [nowDate timeIntervalSinceDate:birthDay];
}
网友评论