美文网首页
OC/iOS 中时间转为字符串

OC/iOS 中时间转为字符串

作者: 闻人歌 | 来源:发表于2018-02-03 10:56 被阅读9次
    • 字符串转时间
    - (NSDate *)dateWithStr:(NSString *)timeStr{
        NSDateFormatter *formatter = [NSDateFormatter new];
        formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
        NSDate *date = [formatter dateFromString:timeStr];
        // 将时间转为当前时区
        NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
        NSInteger interval = [timeZone secondsFromGMTForDate:date];
        NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
        return localeDate;
    }
    
    • 时间转字符串
    - (NSString *)stringWithDate:(NSDate *)date{
        NSDateFormatter *formatter = [NSDateFormatter new];
        formatter.dateFormat = @"YYYY-MM-dd HH:mm:ss";
        
        // 将时间转为当前时区
        NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
        NSInteger interval = [timeZone secondsFromGMTForDate:date];
        NSDate *localeDate = [date  dateByAddingTimeInterval:-interval];
        
        NSString *str = [formatter stringFromDate:localeDate];
        return str;
    }
    

    相关文章

      网友评论

          本文标题:OC/iOS 中时间转为字符串

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