我从字符串转换时得到NSDate null?

时间:2014-02-01 11:09:51

标签: ios iphone objective-c nsdate nsdateformatter

    NSString * string=@"20-02-2014";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd-yyyy"];
    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];

    NSDate *date = [dateFormatter dateFromString:string];

我得到date = null,请帮我找到问题??

2 个答案:

答案 0 :(得分:3)

您的NSDateFormatter错误,您有MM-dd,但您的字符串为dd-mm。 将其更改为:

[dateFormatter setDateFormat:@"dd-MM-yyyy"];

这应该有所帮助。

答案 1 :(得分:-3)

如果您使用的是datePicker,请尝试以下代码:

    datePicker.datePickerMode = UIDatePickerModeDate;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];


[formatter setDateFormat:@"MM dd, YYYY"];
[formatter setDateStyle:NSDateFormatterMediumStyle];

NSString *dateselected=[NSString stringWithFormat:@"%@",[formatter       stringFromDate:datePicker.date]];
[datelabel setText:dateselected];
[formatter release];
[datePicker release];