字符串和日期戳之间的互相转化

2016-08-29  本文已影响16人  江湖闹士

1、将字符串转成日期,再将日期转成时间戳

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];    
[inputFormatter setDateFormat:@"yyy年MM月dd日"];    
NSDate* inputDate = [inputFormatter dateFromString:dateString];
NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[inputDate timeIntervalSince1970]];

2、将时间戳转成时间 再转成字符串

NSTimeInterval time = [model.birthday doubleValue];    
NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setDateFormat:@"yyyy年MM月dd日"];
NSString *currentTime = [dateFormatter stringFromDate:detailDate];

3、根据生日时间戳来计算年龄

NSTimeInterval time = [model.birthday doubleValue];
NSDate *detailDate = [NSDate dateWithTimeIntervalSince1970:time];        
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];        
[dateFormatter setDateFormat:@"yyyy年MM月dd日"];        
NSString *currentTime = [dateFormatter stringFromDate:detailDate];        
_brithdayLabel.text = currentTime;               
NSDate *nowDate = [NSDate date];        
CGFloat duringTime = [nowDate timeIntervalSinceDate:detailDate];        
NSInteger age = (NSInteger)duringTime / (365 * 24 * 60 * 60);               
self.ageLabel.textColor = kGlobalBtn;
NSString *ageStr = [NSString stringWithFormat:@"%ld岁",(long)age + 1];
上一篇下一篇

猜你喜欢

热点阅读