NSDate时区转换

1. 获取系统时区的NSDate对象

打印[NSDate date]得到的是GTM时区对应的时间也就是0时区:2020-07-23 03:45:08 +0000
国内是东8区,因此想获取对应地区则需要加入时区进行计算

获取当前系统对应时区:

NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSLog(@"当前系统时区:%@", [zone name]);

打印结果为:当前系统时区:Asia/Shanghai
获取对应Asia/Shanghai时区的NSDate对象,则要加上与GTM时区的差值:

NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate:date];
NSDate *currentZoneDate = [[NSDate date] dateByAddingTimeInterval:interval];
NSLog(@"%@", currentZoneDate);//打印:2020-07-23 11:45:08 +0000

2. 获取前N天的NSDate对象

还可以获取前/后天NSDate对象:

- (NSDate *)transfrom:(NSDate *)date day:(NSInteger)day{

    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setDay:day];//
    return [[NSCalendar currentCalendar] dateByAddingComponents:adcomps toDate:date options:0];
}

调用:

NSLog(@"今日:%@", date);//打印:2020-07-23 11:45:08 +0000
NSLog(@"昨天:%@", [self transfrom:date day:-1]);//打印:2020-07-22 11:45:08 +0000
NSLog(@"明天:%@", [self transfrom:date day:1]);//打印:2020-07-24 11:45:08 +0000

3. 获取年、月、日、星期

推荐使用:NSCalendar

NSCalendar *calendar = [NSCalendar currentCalendar];

NSDateComponents *components = [Calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond|NSCalendarUnitWeekday fromDate:[NSDate date]];

NSArray *weekChineseArr = @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];

NSLog(@"%zd年", [components year]);
NSLog(@"%zd月", [components month]);
NSLog(@"%zd日", [components day]);
NSLog(@"星期%@", weekChineseArr[[components weekday]]);

//打印:
//2020年
//7月
//23日
//星期四

或者用NSDateFormatter

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd"];

NSLog(@"%@", [formatter stringFromDate:[NSDate date]]);
//打印:2020-07-22

如果本文对你有所帮助记得点个赞哈

推荐阅读更多精彩内容