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,请帮我找到问题??
答案 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];