如何格式化字符串转换2013-01-27T02:31:47 + 08:00进入的NSDate(How

2019-07-18 12:25发布

我曾试过很多次将字符串转换2013-01-27T02:31:47+08:00到NSDate的。 我已经找到了格式指导苹果并复制其代码和尝试,但它不工作。

 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"];

Answer 1:

您的格式应该是@"yyyy-MM-dd'T'HH:mm:ssZZZZZ" 你只需要围绕不会被格式化使用字母单引号。



Answer 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


文章来源: How to format convert the string 2013-01-27T02:31:47+08:00 into NSDate