NSDate在特定日期为空

时间:2013-03-14 04:31:22

标签: iphone ios objective-c nsdate nsdateformatter

我在特定日期获得空字符串,即13/03/2013。这是我的代码:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss a"];
NSDate *myDate = [formatter dateFromString:@"12/03/2013 5:47:00 AM"];
NSDate *myDate1 = [formatter dateFromString:@"13/03/2013 6:25:48 AM"];           

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *datestr = [df stringFromDate:myDate];
NSString *datestr1 = [df stringFromDate:myDate1];
NSLog(@"date object %@,%@",datestr,datestr1);

3 个答案:

答案 0 :(得分:4)

问题是您的日期格式为MM/dd/yyyy HH:mm:ss a。你添加了一个日期:13/03/2013 6:25:48 AM

只有12个月,没有13个月。

将格式更改为:dd/MM/yyyy HH:mm:ss a

答案 1 :(得分:3)

如果你看一下日期格式的标准会更好。 Date and Time Formats

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
    NSDate *myDate = [formatter dateFromString:@"12/03/2013 5:47:00 AM"];
    NSDate *myDate1 = [formatter dateFromString:@"13/03/2013 6:25:48 AM"];  

    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *datestr = [formatter stringFromDate:myDate];
    NSString *datestr1 = [formatter stringFromDate:myDate1];
    NSLog(@"date object %@,%@",datestr,datestr1);

答案 2 :(得分:2)

因为没有第13个月。

13/03/2013是无效日期,因为您使用格式化程序作为MM / dd // yyyy。

试试这个

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"dd/MM/yyyy HH:mm:ss a"];
NSDate *myDate = [formatter dateFromString:@"12/03/2013 5:47:00 AM"];
NSDate *myDate1 = [formatter dateFromString:@"13/03/2013 6:25:48 AM"];

NSLog(@"%@",myDate1);


NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[df setDateFormat:@"yyyy-MM-dd HH:mm"];
NSString *datestr = [df stringFromDate:myDate];
NSString *datestr1 = [df stringFromDate:myDate1];



NSLog(@"date object %@,%@",datestr,datestr1);