NSTimeZone时区
生活随笔
收集整理的這篇文章主要介紹了
NSTimeZone时区
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
前言
NSTimeZone 表示時區(qū)信息。
1、NSTimeZone 時區(qū)的創(chuàng)建
NSTimeZone *zone1 = [[NSTimeZone alloc] init];
// 根據(jù)時區(qū)名稱創(chuàng)建
NSTimeZone *zone2 = [[NSTimeZone alloc] initWithName:@"America/Chicago"];
NSTimeZone *zone3 = [NSTimeZone timeZoneWithName:@"America/Chicago"];
// 根據(jù)時區(qū)縮寫創(chuàng)建
NSTimeZone *zone4 = [NSTimeZone timeZoneWithAbbreviation:@"EST"];
// 根據(jù)零時區(qū)的秒數(shù)偏移量創(chuàng)建
NSTimeZone *zone5 = [NSTimeZone timeZoneForSecondsFromGMT:28800];
2、NSTimeZone 時區(qū)的設置
// 設置默認的時區(qū)
[NSTimeZone setDefaultTimeZone:[[NSTimeZone alloc] initWithName:@"America/Chicago"]];
NSTimeZone *systemZone = [NSTimeZone systemTimeZone];
// 本地時區(qū)可以被修改,而系統(tǒng)時區(qū)不能修改。
NSTimeZone *localZone = [NSTimeZone localTimeZone];
NSTimeZone *defaultZone = [NSTimeZone defaultTimeZone];
// NSCalendar 設置時區(qū)
/*
設置時區(qū),設置為 GMT+8,即北京時間(+8)
*/
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CET"]];
[calendar setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:+28800]];
// NSDateFormatter 設置時區(qū)
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// 設置時區(qū),設置為 GMT
[formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
3、NSTimeZone 時區(qū)的獲取
// 獲取系統(tǒng)時區(qū)
NSTimeZone *zone1 = [NSTimeZone systemTimeZone];
// 獲取本地時區(qū)
NSTimeZone *zone2 = [NSTimeZone localTimeZone];
// 獲取默認時區(qū)
NSTimeZone *zone3 = [NSTimeZone defaultTimeZone];
4、獲取時區(qū)的名稱
// 獲取所有已知的時區(qū)名稱
NSArray *zoneNames = [NSTimeZone knownTimeZoneNames];
NSTimeZone *zone = [NSTimeZone localTimeZone];
// 獲取指定時區(qū)的名稱
NSString *strZoneName = [zone name];
5、獲取時區(qū)的縮寫
// 獲取所有已知的時區(qū)縮寫
NSDictionary *zoneAbbreviations = [NSTimeZone abbreviationDictionary];
NSTimeZone *zone = [NSTimeZone localTimeZone];
// 獲取指定時區(qū)的縮寫
NSString *zoneAbbreviation1 = [zone abbreviation];
// 獲取指定時間所在時區(qū)名稱縮寫
NSString *zoneAbbreviation2 = [zone abbreviationForDate:[NSDate date]];
6、獲取與零時區(qū)的間隔秒數(shù)
NSTimeZone *zone = [NSTimeZone localTimeZone];
// 獲取當前時區(qū)與零時區(qū)的間隔秒數(shù)
NSInteger seconds1 = [zone secondsFromGMT];
// 獲取指定時間所在時區(qū)與零時區(qū)的間隔秒數(shù)
NSInteger seconds2 = [zone secondsFromGMTForDate:[NSDate date]];
7、時區(qū)差值轉(zhuǎn)換
// 得到當前時間(世界標準時間 UTC/GMT)
NSDate *date = [NSDate date];
// 設置系統(tǒng)時區(qū)為本地時區(qū)
NSTimeZone *zone = [NSTimeZone systemTimeZone];
// 計算本地時區(qū)與 GMT 時區(qū)的時間差
NSInteger interval = [zone secondsFromGMT];
// 在 GMT 時間基礎上追加時間差值,得到本地時間
date = [date dateByAddingTimeInterval:interval];
總結(jié)
以上是生活随笔為你收集整理的NSTimeZone时区的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 杨幂主演!《狐妖小红娘》真人版引粉丝不满
- 下一篇: 任达华女儿任晴佳社交媒体晒海边近照被狂赞