NSString 到 NSDate 不断变为 null
我知道这个问题被问了很多次,但我的 NSDate 中总是得到 null 。我有一个像这样的字符串“January 16, 2012 21:44:56”我想将其转换为“January 16, 2012 09:44:56 PM”。我想在转换后的日期中添加 PM,并将 24 小时时间格式转换为 12 小时时间格式。这是我的代码。
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, YYYY HH:ii:ss a"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
I know this been asked for so many times but I always end up getting null in my NSDate. I have a string like this "January 16, 2012 21:44:56" I want to convert it to "January 16, 2012 09:44:56 PM". I want to add a PM in the converted date and convert the 24 hour time format to 12 hour time format. Here's my code.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, YYYY HH:ii:ss a"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:dateString];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如 Ali3n 正确指出的那样,您应该首先将
dateString
的格式设置为格式化程序以获取有效的日期对象。接下来,您应该将格式化程序的格式设置为所需的格式并继续。执行以下操作:As Ali3n correctly pointed out, you should first set the format of
dateString
to the formatter to get a valid date object. Next you should set the formatter's format to the desired one and continue. Do the following:@"MMMM dd, YYYY HH:ii:ss a"
此格式应与 ypu 传递给日期格式化程序的日期匹配..@"MMMM dd, YYYY HH:ii:ss a"
this format should match with the date the ypu are passing to the date formatter ..您的格式字符串中有错误,您还需要告诉格式化程序您的日期字符串所在的区域设置。
设置本地非常重要,因为您的输入中有日期名称。您需要告诉
NSDateFormatter
名称将使用哪种语言。在给出的示例中,它是英文的。我已经让您运行代码而无需在语言未设置为英语的设备上设置本地,它将无法解析日期。There is an error in your format string an also you need to tell the formatter the Locale in which your date string is presented.
Setting the Local is very important since you have an name of a date in your input. You will need to tell the
NSDateFormatter
is wich language the name will be. In the example given it is in english. I've you run you code without setting the local on a device where the language is not set to english it wil fail to parse the date.尝试转义格式字符串中的文字。
Try to escape literals in the format string.
至于您的要求,您必须更改 dateFormatter。检查此 链接了解更多信息。
As for your requirements you have to change the dateFormatter.Check this link for more.