一、給定一個(gè)10位時(shí)間戳,轉(zhuǎn)成不同時(shí)區(qū)的日期
//給定一個(gè)時(shí)間戳
NSString?*test =?@"1652861974”;
//轉(zhuǎn)成北京時(shí)區(qū)下的日期
NSDateFormatter?*beijingFormatter = [[NSDateFormatter?alloc]?init];
[beijingFormatter?setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone?*beijingZone = [NSTimeZone?timeZoneWithAbbreviation:@"GMT+0800"];
[beijingFormatter?setTimeZone:beijingZone];
//轉(zhuǎn)成手機(jī)系統(tǒng)設(shè)置的時(shí)區(qū)(紐約)下的日期
NSDateFormatter?*localFormatter = [[NSDateFormatter?alloc]?init];
[localFormatter?setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone?*localZone = [NSTimeZone?systemTimeZone];//當(dāng)前手機(jī)設(shè)置的是紐約時(shí)區(qū)
[localFormatter?setTimeZone:localZone];
?NSDate* testDate = [NSDate?dateWithTimeIntervalSince1970:[test?longLongValue]];
NSString* beijingDateString = [beijingFormatter stringFromDate:?testDate];//北京時(shí)區(qū)下的日期字符串:“2022-05-18 16:19:34”
NSString* localTimeString = [localFormatter stringFromDate:?testDate];//換成本地(紐約)時(shí)間:2022-05-18 04:19:34
NSLog(@"服務(wù)器返回北京時(shí)間:%@ 轉(zhuǎn)換成本地時(shí)區(qū)時(shí)間:%@ ",?beijingDateString,?localTimeString);
結(jié)果打印:服務(wù)器返回北京時(shí)間:2022-05-18 16:19:34 轉(zhuǎn)換成本地時(shí)區(qū)時(shí)間:2022-05-18 04:19:34
二薪夕、反向驗(yàn)證同一時(shí)刻下世界在不同時(shí)區(qū)的日期返回的時(shí)間戳是相同的:
北京時(shí)區(qū)日期:2022-05-18 16:19:34(以上的beijingDateString對(duì)應(yīng)的)
紐約時(shí)區(qū)日期:2022-05-18 04:19:34(以上的localTimeString對(duì)應(yīng)的)
NSDate?*beiDate = [beijingFormatter?dateFromString:?beijingDateString];
NSTimeIntervalbeiInterval = [beiDate?? timeIntervalSince1970];
NSDate*LocDate = [localFormatter?? dateFromString:?localTimeString];
NSTimeIntervalLocInterval = [LocDate? timeIntervalSince1970];
NSLog(@"原始時(shí)間戳:%@?北京時(shí)區(qū)生成時(shí)間戳:%f??本地時(shí)區(qū)生成時(shí)間戳:%f ",test,(double)beiInterval,(double)?LocInterval);
結(jié)果打铀也摺:?原始時(shí)間戳:1652861974? 北京時(shí)區(qū)生成時(shí)間戳:1652861974.000000 ? 本地時(shí)區(qū)生成時(shí)間戳:1652861974.000000?
驗(yàn)證了同一時(shí)刻雖然處于世界不同時(shí)區(qū)蛤吓,但是拿到的時(shí)間戳是一樣的,前提是轉(zhuǎn)成對(duì)應(yīng)時(shí)區(qū)下的日期即NSDateFormatter要設(shè)置對(duì)應(yīng)的時(shí)區(qū)。