【问题标题】:NSString to NSDate for mm/dd/yyyy hh:mm:ss formatNSString 到 NSDate 用于 mm/dd/yyyy hh:mm:ss 格式
【发布时间】:2011-08-05 17:43:19
【问题描述】:

我得到的日期字符串是这种格式的8/5/2011 1:38:13 PM。如何将其转换为NSDate

我试过了:

[dateFormatter setDateFormat:@"mm/dd/yyyy 'T' hh:mm:ss a"];
NSString *currentDate = [dateFormatter stringFromDate:currentDateString];

它返回nil。有什么想法吗?

【问题讨论】:

    标签: ios date nsstring nsdate nsdateformatter


    【解决方案1】:

    它返回 nil 的原因是因为您调用了错误的方法,日期字符串中没有 T(单引号 ' 中的字符是文字​​),并且 PM 不是“P.M.”。没有破坏它但不完全正确的事情是您试图将月份解析为一分钟,并且您的日期字符串至少可以有 1 位数的月份、日期和小时,因此您不应使用 2 个说明符来填充它们如果您要从日期创建一个字符串。试试这个:

    NSString *currentDateString = @"8/5/2011 1:38:13 PM";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //Set the AM and PM symbols
    [dateFormatter setAMSymbol:@"AM"];
    [dateFormatter setPMSymbol:@"PM"];
    //Specify only 1 M for month, 1 d for day and 1 h for hour
    [dateFormatter setDateFormat:@"M/d/yyyy h:mm:ss a"]; 
    NSDate *currentDate = [dateFormatter dateFromString:currentDateString];
    
    NSLog(@"current date: %@", currentDate);
    //Example of the format using the actual date
    NSLog(@"%@", [dateFormatter stringFromDate:[NSDate date]]);
    [dateFormatter release];
    

    【讨论】:

    • 别忘了发布 dateFormatter :-D
    • 我可能应该在复制粘贴代码之前添加 :),OP 没有将 currentDateString、dateFormatter 代码放在问题中,所以我只是将它添加到顶部 :)
    • [self dateFromString:@"MM/dd/yyyy hh:mm:ss" andDateString:@"08/01/2013 12:14:14"];你好,乔,我没有在 NSDate 对象中得到这个格式日期
    猜你喜欢
    • 2017-07-09
    • 2013-03-21
    • 2015-11-03
    • 2019-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    相关资源
    最近更新 更多