【问题标题】:How to format convert the string 2013-01-27T02:31:47+08:00 into NSDate如何格式化将字符串 2013-01-27T02:31:47+08:00 转换为 NSDate
【发布时间】:2023-03-05 14:56:01
【问题描述】:

我尝试了很多次将字符串2013-01-27T02:31:47+08:00 转换为NSDate。我找到了苹果的formatting guide 并复制了它的代码并尝试了,但它不起作用。

 NSDateFormatter *rfc3339DateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];

    [rfc3339DateFormatter setLocale:enUSPOSIXLocale];
    [rfc3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [rfc3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];

    // Convert the RFC 3339 date time string to an NSDate.
    NSDate *date = [rfc3339DateFormatter dateFromString:@"2013-01-27T02:31:47+08:00"];

【问题讨论】:

    标签: ios objective-c ios6 nsdate nsdateformatter


    【解决方案1】:

    您的格式应为@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"。您只需要在格式化程序不会使用的字母周围加上单引号。

    【讨论】:

      【解决方案2】:
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        [dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
      
        NSString *dateTimeString = @"2013-01-09 16:00:00";
        NSLog(@"DateTimeString = %@", dateTimeString);
      
        NSDate *myDate =[dateFormat dateFromString:dateTimeString];
        NSLog(@"myDate:          %@", myDate);
      

      输出:

        dateTimeString = 2013-01-09 16:00:00
        myDate:        = 2013-01-09 16:00:00 +0000
      

      要向用户显示日期,请将 NSDate 转换为 NSString,使用 stringFromDate,但不要设置时区(以便使用本地时区):

         NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
         [dateFormat2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
      
           NSString *localDateString = [dateFormat2 stringFromDate:myDate];
         NSLog(@"localDateString: %@", localDateString);
      

      输出:

         localDateString: 2013-01-09 17:00:00
      

      【讨论】:

      • 谢谢你的详细解释,但我必须转换确切的格式2013-01-27T02:31:47+08:00,因为它是从服务器返回的:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多