美文网首页
字符串和日期戳之间的互相转化

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

作者: 江湖闹士 | 来源:发表于2016-08-29 22:57 被阅读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];
    

    相关文章

      网友评论

          本文标题:字符串和日期戳之间的互相转化

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