0

我想要这个字符串到 nsdate

“2012-12-25T18:58:57.649Z”

我知道如何将 nsstring 转换为 nsdate,但我找不到正确的格式。我设置了以下格式,但它不起作用。请建议

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
    [dateFormatter setDateFormat:@"yyyy-MM-ddTHH:mm:ss"];
4

1 回答 1

1

希望这有帮助

- (NSDate *)dateFromISO8601:(NSString *)str{
   if(![str isKindOfClass:NSString.class]){
      return nil;
   }

   static NSDateFormatter* sISO8601 = nil;

   if (!sISO8601) {
      sISO8601 = [[NSDateFormatter alloc] init];
      [sISO8601 setTimeStyle:NSDateFormatterFullStyle];
      [sISO8601 setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.S"];
      [sISO8601 setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
  }
  if ([str hasSuffix:@"Z"]) {
      str = [str substringToIndex:(str.length-1)];
  }

  NSDate *d = [sISO8601 dateFromString:str];
  return d;
 }
于 2012-12-26T07:18:02.410 回答