【问题标题】:convert GMT time object to local time iOS将 GMT 时间对象转换为本地时间 iOS
【发布时间】:2015-12-19 11:28:19
【问题描述】:

我想转换从网络服务获得的 GMT 时间。我得到这样的对象

dateTime: {
           date: 23
           day: 3
           hours: 6
           minutes: 13
           month: 8
           nanos: 0
           seconds: 0
           time: 1442988780000
           timezoneOffset: 0
           year: 115
          }

我不知道如何将此对象转换为本地电话时间。

【问题讨论】:

  • 为什么是 115 年?这是基于什么日历? time参数中的值是多少?
  • 第 115 年是 2015 年 (1900 + 115)。

标签: ios swift nsdate gmt


【解决方案1】:

您可以使用NSDateComponentsNSDate。请参阅 Apple 的 Date and Time Programming Guide

【讨论】:

    【解决方案2】:

    Step1- 转换您在Dictionary or Array 中获得的数据 Step2- 通过key-value 对访问字典。 'Step3-' 参考苹果文档中的NSDate

    也试试这个-

    NSString *dateStr = @"2012-07-16 07:33:01";
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init]; 
    [dateFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
    NSDate *date = [dateFormatter1 dateFromString:dateStr];
    NSLog(@"date : %@",date);
    
    NSTimeZone *currentTimeZone = [NSTimeZone localTimeZone];
    NSTimeZone *utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
    
    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:date];
    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:date];
    NSTimeInterval gmtInterval = currentGMTOffset - gmtOffset;
    
    NSDate *destinationDate = [[[NSDate alloc] initWithTimeInterval:gmtInterval sinceDate:date] autorelease];
    
    NSDateFormatter *dateFormatters = [[NSDateFormatter alloc] init];
    [dateFormatters setDateFormat:@"dd-MMM-yyyy hh:mm"];
    [dateFormatters setDateStyle:NSDateFormatterShortStyle];
    [dateFormatters setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatters setDoesRelativeDateFormatting:YES];
    [dateFormatters setTimeZone:[NSTimeZone systemTimeZone]];  
    dateStr = [dateFormatters stringFromDate: destinationDate];
    NSLog(@"DateString : %@", dateStr);
    

    【讨论】:

      猜你喜欢
      • 2013-10-29
      • 2010-09-15
      • 2012-08-28
      • 2011-04-23
      • 2013-05-04
      相关资源
      最近更新 更多