【问题标题】:iOS 9 : Add GMT Time ValueiOS 9:添加 GMT 时间值
【发布时间】:2016-08-29 07:06:08
【问题描述】:

我在 google 上搜索了如何在 Objective-C 中获取 GMT 时间,我得到了这个:

+ (NSString *)GetGMTTime{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];

return [dateFormatter stringFromDate:[NSDate date]];}

有没有办法添加或设置 GMT 时间? (GMT+5)

【问题讨论】:

  • 您需要 GMT + 5:30 或 GMT+5

标签: ios objective-c iphone nsdate nsdateformatter


【解决方案1】:

最灵活的方式是使用timeZoneForSecondsFromGMT。这比使用 GMT+X 之类的字符串更防错

这是一个完整的例子:

+ (NSString *)GetGMTTime{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

    NSTimeZone *gmt = [NSTimeZone timeZoneForSecondsFromGMT:(60*60*5)];
    [dateFormatter setTimeZone:gmt];

    return [dateFormatter stringFromDate:[NSDate date]];

}

返回2016-08-29T12:13(当GMT时间为2016-08-29T7:13

注意:60*60*5 表示5 hours X 60 minutes X 60 seconds

【讨论】:

    【解决方案2】:

    可以这样试试。

     NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+5:30"];
    

    【讨论】:

      【解决方案3】:

      如果您创建NSDate 实例,则默认情况下它将以UTC or GMT 格式返回日期。

      现在,当您通过任何日期格式化程序将此日期转换为字符串时,返回的字符串(日期)将采用本地时区(即设备的时区)。

      您可以使用其名称创建自定义时区以获取该时区的日期。

        NSDate *date = [NSDate date]; //give current date in UTC or GMT
      NSLog(@"current date in gmt : %@",date);
      
      NSDateFormatter *df = [[NSDateFormatter alloc]init];
      [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
      
      NSString *dateInStrFormat = [df stringFromDate:date];  // this date(string format) will be in current timezone that was set in your device and
      
      NSLog(@"current date in local or device's default timezone : %@",dateInStrFormat);
      
      NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Kolkata"];
      
      NSLog(@"timezone : %@",timeZone);
      
      [df setTimeZone:timeZone];
      
      NSString *dateInCustomTimeZone = [df stringFromDate:date]; // this will return date in Asia/Kolkata's timezone
      
      NSLog(@"date in custom timezone : %@",dateInCustomTimeZone);
      

      NSLog(@"timezone : %@",timeZone); 会打印出类似Asia/Kolkata (IST) offset 19800 的内容。 19800 是偏移量,如果你将它与3600 分开,那么你会得到与gmt 的差异,比如(+/- 5.30 etc)

      Link for different timezone names

      或者你可以得到时区,

        NSTimeZone *timezone1 = [NSTimeZone timeZoneWithName:@"GMT+5:30"];
      NSLog(@"timezone : %@",timezone1);
      
      NSTimeZone *timeAone2 = [NSTimeZone timeZoneForSecondsFromGMT:60*60*5.5];
      NSLog(@"timezone : %@",timeAone2);
      

      【讨论】:

        猜你喜欢
        • 2013-08-13
        • 2014-06-21
        • 1970-01-01
        • 1970-01-01
        • 2018-02-03
        • 2015-12-19
        • 1970-01-01
        • 1970-01-01
        • 2013-09-21
        相关资源
        最近更新 更多