【问题标题】:NSDateFormatter how can I format this date?NSDateFormatter 如何格式化这个日期?
【发布时间】:2012-08-16 09:51:06
【问题描述】:

我正在尝试格式化如下所示的 NSString:

@"2012-07-19T02:58:33Z"

到具有以下格式的 NSDate:

@"MMMM dd, yyyy HH:mm a"

NSDateFormatter 总是返回 nil,我认为这是因为它无法将当前格式的 NSString 转换为所需的格式。这是我的代码:

 NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
        NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formatter setLocale:enUSLocale];
        NSDate *date = [formatter dateFromString:dateString];

我需要以不同的格式存储日期吗?我可以使用当前的 NSString 进行这种转换吗?

谢谢!

【问题讨论】:

    标签: iphone objective-c cocoa-touch nsdateformatter


    【解决方案1】:

    您的 dateFormatter 与您的 dateString 不匹配...试试这个

    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
    NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [formatter setLocale:enUSLocale];
    NSDate *date = [formatter dateFromString:dateString];
    
    [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
    dateString=[formatter stringFromDate:date];
    

    现在 dateString 包含“2012 年 7 月 19 日 02:58 AM”

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      试试看。

      NSString *myDateString=@"2012-07-19T02:58:33Z";//@"2009-07-06T17:42:12";
      NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
      
      [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
       NSDate *myDate = [[NSDate alloc] init];
       myDate = [dateFormatter dateFromString:myDateString];
       NSLog(@"MyDate is: %@", myDate);
      

      【讨论】:

        【解决方案3】:

        你的问题已经是answered了。

        将您的字符串以原始字符串的格式存储在 NSDate 中:

        NSString *originalDateString = @"2012-07-19T02:58:33Z";
        NSDateFormatter *originalFormatter = [[NSDateFormatter alloc]init];
         [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
        
        NSLocale *enUSLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [formatter setLocale:enUSLocale];
        NSDate *originalDate = [formatter dateFromString:originalDateString];
        
        NSDateFormatter *newFormatter = [formatter setDateFormat:@"MMMM dd, yyyy HH:mm a"];
        NSString *newDateString = [formatter stringFromDate:originalDate];
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多