NSString到NSDate [英] NSString to NSDate

查看:102
本文介绍了NSString到NSDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含当前日期的字符串:

I got a string that contains the current date by using this :

NSString *date = [[NSDate date] description];

另一点,我想从这个字符串中检索日期,我使用下面的代码: / p>

At a different point I want to retrieve the date from this string and I used the following code:

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehaviorDefault];
[dateFormatter setDateFormat:@"YYYY-MM-DD HH:MM:SS ±HHMM"];

NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:<NSString containing date>];

我得到 dateFromString nil 0x0。

推荐答案

你不能发明格式化字符串语法并期望它工作;您需要实际使用已记录的格式。 (确切地说,MM意味着月,分钟和GMT偏移分钟全部同时?)

You can't invent format string syntax and expect it to work; you need to actually use a documented format. (Seriously, "MM" meaning "month", "minute" and "GMT offset minutes" all at the same time?)

由于文档点则10.4格式化程序使用 Unicode格式字符串

As the documentation points out, the 10.4 formatters use Unicode format strings.

请尝试yyyy-MM-dd HH:mm:ss ZZZ。

Try "yyyy-MM-dd HH:mm:ss ZZZ" instead.

此外,Objective-C源代码是ASCII 。不要把字符放在那里,并期望它在任何上下文中工作;而是使用字符串文件。

Also, Objective-C source is ASCII. Don't put characters like ± in there and expect it to work in any context; instead, use strings files.

这篇关于NSString到NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆