OC/iOS 中时间转为字符串

  • 字符串转时间
- (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 中时间转为字符串)