Datetime format from iPhone settings and GMT offset

六眼飞鱼酱① 提交于 2019-11-29 13:15:16

You can use NSDateFormatter to achieve this.

NSString *dateString = @"2013-05-28 10:56:31";

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

//Special Locale for fixed dateStrings
NSLocale *locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];
[formatter setLocale:locale];

//Assuming the dateString is in GMT+00:00
//formatter by default would be set to local timezone 
NSTimeZone *timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
[formatter setTimeZone:timeZone];

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

NSDate *date =[formatter dateFromString:dateString];

//After forming the date set local time zone to formatter    
NSTimeZone *localTimeZone = [NSTimeZone localTimeZone];
[formatter setTimeZone:localTimeZone];

NSString *newTimeZoneDateString = [formatter stringFromDate:date];
NSLog(@"%@",newTimeZoneDateString);

A few pointers for using dateFormatter.

  1. If the string don't contain any information about timezone and it is not in same timezone as in the device always set the timezone to the dateFormatter.
  2. For fixed format dateStrings always use en_US_POSIX locale
  3. NSDate when logged in console always show in GMT+00:00. NSDate don't have timezone, it just differs when represented in different timezone.
  4. Convert the formed date to any timezone, by setting new timezone to formatter. Formatter never changes the date it just recalculates how it will be represented in this new timezone.

See the documentation about NSDateFormatter, specifically dateFromString, which returns "A date representation of string interpreted using the receiver’s current settings."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!