简体   繁体   English

将String转换为NSDate总是为零

[英]Convert String to NSDate always nil

I want to covert from a NSString to NSDate object. 我想从NSString转换为NSDate对象。 My string is : @"01/01/2013 . 我的字符串是: @"01/01/2013

Here is the code to convert the string to NSDate: 以下是将字符串转换为NSDate的代码:

- (NSDate*) formatDateTimeFromString: (NSString* ) string{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSDate* date=  [dateFormatter dateFromString:string    ];
    return date;
}

I debug into the function and see that the date object is always nil. 我调试了该函数,然后看到date对象始终为nil。 Did I have any mistake? 我有什么错误吗?

Your date formatter is wrong (might be hard to see at first) 您的日期格式错误(一开始可能很难看)

Change 更改

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

to

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM