NSString 到 NSDate [英] NSString to NSDate

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

问题描述

我得到了一个包含当前日期的字符串:

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

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

在另一个点我想从这个字符串中检索日期,我使用了以下代码:

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.我做错了什么?

I am getting dateFromString as nil 0x0. What am I doing wrong?

推荐答案

您不能发明格式字符串语法并期望它起作用;您需要实际使用文档格式.(说真的,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天全站免登陆