【问题标题】:iOS Convert NSString to NSDate alway niliOS 将 NSString 转换为 NSDate 总是为零
【发布时间】:2015-02-24 13:03:55
【问题描述】:

我正在尝试将字符串转换为NSdate。字符串日期为“12/27/2014 07:42:00 AM +0000

这是我的代码:

NSDate *date =[[NSDate alloc] init];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MM/dd/yyyy HH:mm:ss a";
date = [ dateFormatter dateFromString:dateString];

日期值始终为零。你们中的任何人都知道我做错了什么吗?

非常感谢您的帮助。

【问题讨论】:

  • [[NSDate alloc] init] 完全没有意义。

标签: ios objective-c nsstring nsdate


【解决方案1】:

试试

dateFormatter.dateFormat = @"MM/dd/yyyy hh:mm:ss a Z";

HH 是 24 小时制的,并且与 a 发生冲突。 Z 代表时区偏移量。

查看说明符:http://unicode.org/reports/tr35/tr35-6.html#Date_Field_Symbol_Table


NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"MM/dd/yyyy hh:mm:ss a Z";
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
// see https://developer.apple.com/library/ios/qa/qa1480/_index.html


NSDate *date = [dateFormatter dateFromString:dateString];

【讨论】:

    【解决方案2】:
        NSString *str =@"12/27/2014 07:42:00 AM +0000";        
        NSDateFormatter *sdateFormatter = [[NSDateFormatter alloc] init];
        sdateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
        [sdateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss a Z'"];
    
        NSDate *sdate = [sdateFormatter dateFromString:str];
        NSLog(@"%@",[sdateFormatter stringFromDate:sdate]);
    

    【讨论】:

      猜你喜欢
      • 2014-12-10
      • 2011-04-24
      • 2017-04-23
      • 2021-09-11
      • 2015-08-01
      • 2016-09-01
      相关资源
      最近更新 更多