【问题标题】:Convert NSString to NSDate with new format使用新格式将 NSString 转换为 NSDate
【发布时间】:2012-08-01 14:24:14
【问题描述】:

这个问题被问了很多,但我找不到我的问题的解决方案。

我想要什么: 将作为 NSString 给出的日期转换为具有完全不同格式的 NSDate。 我想将Tue, 31 Jul 2012 10:15:00 GMT 转换为2012-07-31 10:15:00 +0000

我的代码

NSString *startDateString = @"Tue, 31 Jul 2012 10:15:00 GMT"; //in real from a server

NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];

NSDate *startDate = [formatter dateFromString:startDateString];
[formatter setDateFormat:@"yyy-MM-dd HH:mm:ss'Z'"];

NSString *endDateString = [formatter stringFromDate:startDate];
NSDate *endDate = [formatter dateFromString:endDateString];

问题endDatenil

编辑
发现了一个奇怪的行为。
当我将第一个 dateFormat 更改为 @"EEE, dd MMM yyy HH:mm:ss 'GMT'"(添加 GMT)时,endDate 的输出是正确的,但 only 在模拟器中。在设备上它仍然为零。
使用不带“GMT”的 dateFormat 时,模拟器和设备上的值为零。

【问题讨论】:

    标签: ios nsdateformatter


    【解决方案1】:

    这对我来说效果很好,你可以使用它:

    NSString *startDateString = @"Tue, 31 Jul 2012 10:15:00 GMT"; //in real from a server
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
    [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ssZZZ"]; // SPOT the difference in this line
    
    NSDate *startDate = [formatter dateFromString:startDateString];
    [formatter setDateFormat:@"yyy-MM-dd HH:mm:ssZZZ"]; // and SPOT the difference in this line
    
    NSString *endDateString = [formatter stringFromDate:startDate];
    NSDate *endDate = [formatter dateFromString:endDateString];
    
    NSLog(@"%@", endDate);
    

    endDate 是:

    2012-07-31 10:15:00 +0000
    

    更新 #1

    它已仅在真实设备上测试过

    【讨论】:

    • 谢谢!这行得通。我必须将格式化程序的语言环境设置为 en_US:[formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]],因为我的语言环境默认为“de_DE”,这似乎是错误的。
    【解决方案2】:

    在转换之前添加以下内容

    [formatter setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"]];
    

    【讨论】:

      猜你喜欢
      • 2012-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 2011-04-24
      • 2017-04-23
      相关资源
      最近更新 更多