[objc/swift] Timezone 사용법

천현철·2021년 1월 21일
0

iOS

목록 보기
9/51

objc:

NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm"];

NSString *localDateString = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"date = %@", localDateString); //date = 14/08/2020 14:43

NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
NSLog(@"Name: %@", localTimeZone.name); //Name: Asia/Seoul

NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:localTimeZone.secondsFromGMT];
NSLog(@"1. GMT: %@", timeZone.abbreviation); //1. GMT: GMT+9
NSLog(@"2. GMT: %@", timeZone.description);	//2. GMT: GMT+0900 (GMT+9) offset 32400
NSLog(@"3. GMT: %@", timeZone.name);		//3. GMT: GMT+0900
NSLog(@"GMT offset(sec): %ld", (long)[NSTimeZone localTimeZone].secondsFromGMT);
//GMT offset(sec): 32400

//gmt offset 분단위로 환산
NSInteger offsetInMillis = [NSTimeZone localTimeZone].secondsFromGMT;
NSString *offset = [NSString stringWithFormat:@"%d",abs((int)offsetInMillis/60)];
NSLog(@"GMT offset(min): %@", offset);
//GMT offset(min): 540

swift:

print(TimeZone.current.secondsFromGMT()/60) //540

let timeZone = NSTimeZone.init(forSecondsFromGMT: TimeZone.current.secondsFromGMT())
print(timeZone.name) //GMT+0900

print(TimeZone.current.identifier) //Asia/Seoul

출처
https://stackoverflow.com/questions/27053135/how-to-get-a-users-time-zone

profile
기도하지말고 행동하라

0개의 댓글