【问题标题】:Iphone date formatiphone日期格式
【发布时间】:2014-04-22 23:37:58
【问题描述】:

我试图将时间从GMT+7 格式化为GMT+3

我正在构建一个具有特定国家/地区世界时钟的应用程序(用户将在GMT+7,我想代表GMT+3 时间)

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setLocale:[NSLocale currentLocale];    
NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:118800];    
NSLocale *USLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];         
[dateFormatter setLocale:USLocale];    
NSLog(@"Date for locale %@: %@",
[[dateFormatter locale] localeIdentifier], [dateFormatter stringFromDate:date]);

我深入研究了NSDate 类参考,但我不明白如何制作它。

如果有人可以帮助我,我将不胜感激。

【问题讨论】:

标签: ios ios7 nsdate nsdateformatter nstimezone


【解决方案1】:

有 2 个重要的参数分别起作用:时间和时区。

例如:越南使用 GMT+7

如果我知道越南的时间是上午 9:00,那么 GMT 时间就是凌晨 2:00。

当您从设备获取日期时,您将获取时间和时区:YYYY-MM-DD HH:MM:SS ±HHMM。其中 ±HHMM 是与 GMT 的时区偏移量,以小时和分钟为单位。

通常你只是在使用时间。但是,使用NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"],您可以告诉NSDateFormatter 您想要与您当地时区相关的GMT 时间。所以,与:

NSDateFormatter *dt = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
[dt setTimeZone:timeZone];

您可以获得当地时区日期的 GMT 日期。

所以,如果您有 GMT+7: 9:00 AM 并且您想打印 GMT+3: 5:00 AM,您有 3 种可能性:

NSDate *localDate = [NSDate date];

选项 1

添加-4小时的时间间隔:

NSTimeInterval secondsInFourHours = -4 * 60 * 60;
NSDate *dateThreeHoursAhead = [localDate dateByAddingTimeInterval:secondsInFourHours];
NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setDateFormat:@"h:mm a"];
NSLog(@"GMT+7(-4) = %@", [dt stringFromDate:dateThreeHoursAhead]);

这是最简单的方法。如果您总是在 GMT+7 并且您需要 GMT+3,则这是 -4 小时的时间间隔。

选项 2

将时间设置为 GMT 时区,然后添加一个 +3 小时的时间间隔。最简单的方法是先添加 3 小时,然后将时间移至 GMT:

NSTimeInterval secondsInThreeHours = 3 * 60 * 60;
NSDate *dateThreeHoursAhead = [localDate dateByAddingTimeInterval:secondsInThreeHours];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat:@"h:mm a"];
NSString *date = [dateFormatter stringFromDate:dateThreeHoursAhead];
NSLog(@"GMT+3 = %@", date);

选项 3

这是更好的选择。 GMT+3 是 EAT(东非时间),您可以将时区设置为 EAT:[NSTimeZone timeZoneWithName:@"EAT"]

NSDateFormatter *dt = [[NSDateFormatter alloc] init];
[dt setDateFormat:@"h:mm a"];
NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"EAT"];
[dt setTimeZone:timeZone];
NSLog(@"EAT = %@", [dt stringFromDate:localDate]);

选项 3 始终检索 GMT+3

An example code here.

【讨论】:

  • 首先感谢您的帮助,我忘记了在我的国家有一个夏季时钟和冬季时钟,这使它更加复杂,我可以添加一个 api 或类似的东西?
  • 据我了解,您的当地时间有冬/夏时钟,而 GMT+3 没有。我有一个与埃塞俄比亚时间 (GMT+3) 类似的应用程序,您的本地时间将与 NSDate 的这一部分一起自动上传:±HHMM。然后你应该只使用选项 2:增加 3 小时并将 NSDate 移动到 GMT。
  • 无论如何,也许选项 3 也有效。您可以在 Mac 中手动更改日期和时区来测试它。系统偏好设置/日期和时间/日期和时间或时区
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2013-01-05
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
相关资源
最近更新 更多