iOS 时区

作者: 八月就是八月 | 来源:发表于2017-04-10 11:58 被阅读803次

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

基础知识

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 时区

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

  • iOS 获取时区

       最近做的项目要海外用,与设备交互,比如定时延时任务什么的,就不能只按照国内的时区来了,不然国外用着就炸了。 ...

  • iOS 当前时区

  • 消息推送(本地推送)

    zone 时区 badge 图标 //iOS8之后需要注册通知类型包含哪些(声音,图标文字,文本)信息 /* UI...

  • iOS 时间戳 时区

    时间戳 时间戳(Unix)是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日...

  • iOS - OC NSTimeZone 时区

    前言 1、NSTimeZone 时区的创建 2、NSTimeZone 时区的设置 3、NSTimeZone 时区的...

  • 浅谈iOS的时区

    TC、GMT、UTC TC(Universal Time)世界时, 是指格林尼治所在地的标准时间。个人认为可以把它...

  • iOS swift 时间戳获取转换

    首先说明一下,在ios中获取到的时区是计算过夏令时的,比如:在以华盛顿(美国)为例,时区为西五区,获取后为西四区,...

  • iOS将其他时区转换当前系统时区

    将其他时区转换当前系统时区

  • 05 Linux常用命令

    0. 修改Linux时区 查看当前时区命令 : "date -R" 复制相应的时区文件,替换系统时区文件;或者创建...

网友评论

    本文标题:iOS 时区

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