0

我得到一个特定日期的空字符串,即 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);
4

3 回答 3

4

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

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

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

于 2013-03-14T04:47:00.370 回答
3

如果您查看日期格式的标准会更好。日期和时间格式

    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);
于 2013-03-14T04:34:44.740 回答
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);
于 2013-03-14T04:36:29.183 回答