【问题标题】:NSDateFormatter is not working with PET formatNSDateFormatter 不适用于 PET 格式
【发布时间】:2014-09-30 12:36:28
【问题描述】:

我想用时区 PET 解析来自 API 的日期字符串。所以我创建了 NSDateFormatter 并将字符串转换为日期,但不幸的是它不起作用。结果我得到了零。有什么解决方法吗?

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
[formatter setDateFormat:@"EEE MMM dd HH:mm:ss yyyy zz"];
NSDate *newStartDate = [formatter dateFromString:@"Mon Sep 29 14:40:00 2014 PET"];

NSLog(@"newStartDate - %@",newStartDate);

【问题讨论】:

  • NSTimeZone knownTimeZones 返回可识别的时区列表。赔率是“PET”不在列表中。
  • 但是使用 [NSTimeZone timeZoneWithAbbreviation] 会得到一个列表,其中有 PET。如果我们使用 [NSTimeZone knownTimeZoneNames];那么“美国/利马”就是 PET
  • NSDateFormatter 往往对读取带有“EEE”的格式感到挑剔——有时它有效,有时无效。最好在解析之前从字符串中去除星期几的值(当然,适当地修改格式字符串)。另外,请注意"locale feature"

标签: ios objective-c iphone nsdate nsdateformatter


【解决方案1】:

试试下面的函数。它会工作的......

     NSDate *newStartDate = [self dateFromString:@"Mon Sep 29 14:40:00 2014 PET"];

     NSLog(@"newStartDate - %@",newStartDate);


    - (NSDate *)dateFromString:(NSString*)inDateString
    {
       NSDateFormatter  *pivotalDateFormatter = [[NSDateFormatter alloc] init];
       NSDate * dateToBeReturned = nil;
       [pivotalDateFormatter setDateFormat:@"EEE MMM dd HH':'mm':'ss yyyy z"];

       NSString * timezoneAbbreviation = [[inDateString componentsSeparatedByString:@" "]       lastObject];
       NSTimeZone *timeZone = [NSTimeZone timeZoneWithAbbreviation:timezoneAbbreviation];
      if (timeZone)
      {
        NSString *gmtTime = [inDateString    stringByReplacingOccurrencesOfString:timezoneAbbreviation withString:@"GMT"];
        dateToBeReturned = [[pivotalDateFormatter dateFromString:gmtTime] dateByAddingTimeInterval:-timeZone.secondsFromGMT];
      }
    return dateToBeReturned;
   }

【讨论】:

    【解决方案2】:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    NSDate *newStartDate = [NSDate date];

    NSString *newStartDateStr = [dateFormatter stringFromDate:newStartDate];

    现在更改 dateformatter 日期格式

    [dateFormatter setDateFormat:@"EEE MMM dd HH:mm:ss yyyy zz"]; //set dateformat as per ur requirement

    newStartDate = [dateFormatter dateFromString:newStartDateStr];

    NSLog(@"%@", newStartDate);

    你会得到你需要的日期格式

    快乐编码

    【讨论】:

    • 最初我没有 NSDate。所以只使用 NSDateFormatter 我可以将 NSString 转换为 NSDate。
    • 通常 dateformatter 有一些默认的 dateformat...所以你首先必须将你的日期转换为该 dateformat 中的字符串,然后更改 dateformat 你会得到你需要的 dateformat
    • 正如我最初所说的,我没有日期,我只有字符串,所以我需要将该字符串转换为日期??
    • 将该字符串放入日期变量中,而不将任何日期格式设置为 dateformatter,然后将该日期转换为另一个字符串。设置您所需的日期格式。并从该字符串中获取您所需的日期
    • @sreekanthk - 你没有任何意义。当您提供明确的日期格式时,它会覆盖任何“默认格式”。从 NSDate 转换为字符串再转换回 NSDate 证明不了任何事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-27
    • 2015-10-14
    • 1970-01-01
    • 2013-12-03
    • 2011-11-27
    • 1970-01-01
    相关资源
    最近更新 更多