iOS 时区

      由于项目之前对时区没有做过统一的处理,导致国外友人使用起来不是很方便,借此机会,咱们聊一聊时区的事。

基础知识

1.获取所有已知的时区名称

NSArray *zoneArray = [NSTimeZone knownTimeZoneNames];

for(NSString *str in zoneArray){

NSLog(@"%@",str);

}

运行结果为:

注意:没有北京时区

2.返回时区名称和缩写

NSTimeZone *zone = [NSTimeZone localTimeZone];

NSString *strZoneName = [zone name];

NSString *strZoneAbbreviation = [zone abbreviation];

NSLog(@"名称 是 %@",strZoneName);

NSLog(@"缩写 是 %@",strZoneAbbreviation);

运行结果:


3.系统时区,本地时区

[NSTimeZone setDefaultTimeZone:[[NSTimeZone alloc] initWithName:@"America/Chicago"]];

NSTimeZone *systemZone = [NSTimeZone systemTimeZone];

NSTimeZone *localZone = [NSTimeZone localTimeZone];

NSLog(@"系统时区%@",systemZone);

NSLog(@"本地时区%@",localZone);

运行结果:


其中,系统时区不能通过代码来进行更改。

4.得到当前时区与零时区的间隔秒数

NSTimeZone *zone = [NSTimeZone localTimeZone];

NSInteger seconds = [zone secondsFromGMT];

NSLog(@"%ld",seconds);

运行结果:

5.根据上小结根据与零时区的秒数偏移返回一个新时区对象(设置的为上海时区)

NSTimeZone* timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8*3600];

演练

无论身在何处,系统时间设置为北京时间

NSTimeZone *zone = [NSTimeZone localTimeZone];

UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 30)];

titleLab.text =[NSString stringWithFormat:@"当前时区:%@",[zone name]];

titleLab.backgroundColor = [UIColor grayColor];

[self.view addSubview:titleLab];

NSDate *date = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];

//强制设为北京时区

NSTimeZone* timeZone = [NSTimeZone timeZoneForSecondsFromGMT:8*3600];

[dateFormatter setTimeZone:timeZone];

UILabel *dateLab = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 200, 30)];

dateLab.backgroundColor = [UIColor lightGrayColor];

dateLab.text = [dateFormatter stringFromDate:date];

[self.view addSubview:dateLab];

运行结果:


结束,就这样

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS开发中,经常会遇到各种各样的时间问题,8小时时差,时间戳,求时间间隔,农历等等。解决办法网上比比皆是,但大...
    真巧了_嘿阅读 2,825评论 0 7
  • iOS开发中,经常会遇到各种各样的时间问题,8小时时差,时间戳,求时间间隔,农历等等。解决办法网上比比皆是,但大多...
    小李龍彪阅读 6,455评论 1 6
  • 下午下班的时候,老张发来信息:不回家吃饭了,早上买的新鲜排骨和玉米,放在门卫,记得拿。 电动车篓里装着大饭盒,车架...
    垛垛阅读 220评论 0 0
  • 每日奇葩,自娱自乐
    艳青阅读 230评论 10 2