xcode NSDate dateFromString 已弃用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3402367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSDate dateFromString deprecated?
提问by Ian McIntyre Silber
I'm trying to use the NSDate dateFromString method but I'm getting an warning and it's crashing the app. The code looks like:
我正在尝试使用 NSDate dateFromString 方法,但我收到警告并且它使应用程序崩溃。代码如下:
NSString *pickerDate = [NSString stringWithFormat:@"%@", timeSelector.date];
NSDate *defaultDate = [NSDate dateFromString:pickerDate];
The warning is:
警告是:
'NSDate' may not respond to '+dateFromString'.
It appears that method is deprecated (in the midst of an upgrade from XCode 2 to 3.
似乎该方法已被弃用(在从 XCode 2 升级到 3 的过程中)。
What alternate method can I use to create a date from a string?
我可以使用什么替代方法从字符串创建日期?
回答by Nick Forge
NSDateFormatter
is the intended way for you to get an NSDate
from an NSString
.
NSDateFormatter
是您NSDate
从NSString
.
The most basic usage is something like this:
最基本的用法是这样的:
NSString *dateString = @"3-Aug-10";
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
dateFormatter.dateFormat = @"d-MMM-yy";
NSDate *date = [dateFormatter dateFromString:dateString];
回答by shrinetree
I had a same problem. I changed the dateFormat from @"YYYY/M/d H:m:s" to @"YYYY/MM/dd HH:mm:ss" as follows. Then it works on my iPhone 4. (Xcode 4.5 for iOS 6.)
我有同样的问题。我将 dateFormat 从 @"YYYY/M/d H:m:s" 更改为 @"YYYY/MM/dd HH:mm:ss" 如下。然后它可以在我的 iPhone 4 上运行。(适用于 iOS 6 的 Xcode 4.5。)
NSDateFormatter *dateFormatter1;
NSString *dateStr1=@"";
NSDate *gantanDate1;
dateFormatter1 = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter1 setLocale:[NSLocale systemLocale]];
[dateFormatter1 setTimeZone:[NSTimeZone systemTimeZone]];
dateFormatter1.dateFormat=@"YYYY/MM/dd HH:mm:ss";
dateStr1=@"2012/1/1 00:00:00"];
// in his case, dateStr1=pickerDate;
gantanDate1 = [dateFormatter1 dateFromString:dateStr1];
回答by SURESH SANKE
Hi Silber everyone says the same thing to convert the string date to date object.Try this i think you have used two date formatters in two places where you are saving date to string and getting date from string.right try to use the same date formatters in both places. It will solve your problem.
嗨 Silber 每个人都说同样的事情将字符串日期转换为日期对象。试试这个我认为你在两个地方使用了两个日期格式化程序,你将日期保存到字符串并从字符串中获取日期。尝试使用相同的日期格式化程序在这两个地方。它会解决你的问题。