iPhone设置和GMT偏移的日期时间格式 [英] Datetime format from iPhone settings and GMT offset

查看:326
本文介绍了iPhone设置和GMT偏移的日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有日期时间格式的字符串,例如: 2013-05-28 10:56:31

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

如何将此字符串格式化为iPhone默认格式? (在iPhone设置中)

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

如何设置GMT的日期时间加上时移偏移(在iphone中设置)。例如GMT + 1

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

这可能吗?

推荐答案

您可以使用NSDateFormatter来实现此目的。

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);

使用dateFormatter的一些指示。

A few pointers for using dateFormatter.


  1. 如果字符串不包含任何有关时区的信息,并且它与设备中的时区不同,则始终将时区设置为dateFormatter。

  2. 对于固定的格式dateStrings始终使用 en_US_POSIX 区域设置

  3. 的NSDate在控制台登录时始终显示在GMT + 00:00。 NSDate没有时区,只是在不同时区表示时有所不同。

  4. 通过将新时区设置为格式化程序,将形成的日期转换为任何时区。 Formatter永远不会更改日期,只会重新计算它在新时区中的表示方式。

  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.

这篇关于iPhone设置和GMT偏移的日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆