iOS时间戳与日期转换

背景:之前写过一篇关于时间转换问题的文章,是通过类别来做的。在使用过程中发现以下几点不方便之处,故更改为继承的方式来实现。

1.手机系统切换时区后会有异常错误
2.日期转换过程中针对时区、时间风格的可定制性很小

#import 

NS_ASSUME_NONNULL_BEGIN

@interface ConvertDateFormatter : NSDateFormatter

- (instancetype)initWithDateFormat:(nullable NSString *)dateFormat timeZone:(nullable NSTimeZone *)timeZone;

/// 时间转换为字符串
- (NSString *)dateConverToTimeStr:(NSDate *)date;

/// 时间转换为时间戳
- (double)dateConverToTimeStamp:(NSDate *)date;

/// 时间戳转换为时间字符串
- (NSString *)timeStampConverToTimeStr:(double)timeStamp;

/// 时间戳转换为时间
- (NSDate *)timeStampConverToNSDate:(double)timeStamp;

/// 时间字符串转换为时间戳
- (double)timeStrConverToTimeStamp:(NSString *)timeStr;

@end

NS_ASSUME_NONNULL_END
#import "ConvertDateFormatter.h"

@implementation ConvertDateFormatter

#pragma mark --- instancetype
- (instancetype)initWithDateFormat:(nullable NSString *)dateFormat timeZone:(nullable NSTimeZone *)timeZone {
    self = [super init];
    if (!self) return nil;
    // 设置默认dateFormat
    if (!dateFormat) dateFormat = @"YYYY-MM-dd HH:mm:ss";
    // 设置默认timeZone
    if (!timeZone) timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    
    self.dateFormat = dateFormat;
    self.timeZone = timeZone;
    
    return self;
}
- (instancetype)init {
    return [self initWithDateFormat:nil timeZone:nil];
}


#pragma mark --- conver
- (NSString *)dateConverToTimeStr:(NSDate *)date {
    return [self stringFromDate:date];
}

- (double)dateConverToTimeStamp:(NSDate *)date {
    NSTimeInterval stamp = [date timeIntervalSince1970];
    return stamp;
}

- (NSString *)timeStampConverToTimeStr:(double)timeStamp {
    NSDate *date = [self timeStampConverToNSDate:timeStamp];
    NSString *timeStr = [self dateConverToTimeStr:date];
    return timeStr;
}

- (NSDate *)timeStampConverToNSDate:(double)timeStamp {
    return [NSDate dateWithTimeIntervalSince1970:timeStamp];
}

- (double)timeStrConverToTimeStamp:(NSString *)timeStr {
    NSDate *date = [self dateFromString:timeStr];
    double timeStamp = [self dateConverToTimeStamp:date];
    return timeStamp;
}
@end

使用

// 以下测试均为北京时间
    NSString *testTimeStr = @"2019-11-13 15:03:16";
    double testTimeStamp = 1573628596;
//    ConvertDateFormatter *formatter = [[ConvertDateFormatter alloc]initWithDateFormat:@"YYYY-MM-dd HH:mm:ss" timeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    ConvertDateFormatter *formatter = [[ConvertDateFormatter alloc]init];
    
    NSDate *strToDate = [formatter dateFromString:testTimeStr];
    NSDate *timeStampToDate = [formatter timeStampConverToNSDate:testTimeStamp];
    double timeStamp = [formatter timeStrConverToTimeStamp:testTimeStr];
    NSLog(@"strToDate:  %@",strToDate);
    NSLog(@"timeStampToDate:    %@",timeStampToDate);
    NSLog(@"timeStamp:  %.0f",timeStamp);

在使用过程中有问题的话,还望评论中告知,多谢

你可能感兴趣的:(iOS时间戳与日期转换)