Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

ios - Datetime format from iPhone settings and GMT offset

I have string with date time format e.g.: 2013-05-28 10:56:31

How can I format this string to the iPhone default format? (in iPhone settings)

And how to set datetime in GMT plus time shift offset (set in iphone too). e.g. GMT+1

Is this possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...