Dateformatter从字符串获取日期 [英] Dateformatter to get Date From String

查看:93
本文介绍了Dateformatter从字符串获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的字符串是这样的,2012-12-08 17:00:00.0.现在,我正在尝试使用NSDate格式化程序从此字符串中检索日期.我的代码是

My string is something like this, 2012-12-08 17:00:00.0. Now I am trying to retrieve date from this string by using NSDate formatter. My code is

NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-dd-MM hh:mm:ss"]; 
NSDate *date1 = [df dateFromString:@"2012-12-08 17:00:00.0"];
NSLog(@"%@ %@",date1);
[df release];

但是我得到的仅仅是空值.

But all I am getting is null value alone..

我已经尝试过几种类型的dateFormatter,例如yyyy/mm/dd hh:mm:ssYYYY-DD-MM HH:MM:SS ..但仍然没有用.任何建议都将不胜感激.

I have tried several types to dateFormatter like, yyyy/mm/dd hh:mm:ss, YYYY-DD-MM HH:MM:SS.. but still no use.. Any suggestion will be appreciated.

推荐答案

假设您只是错误地在帖子中输入了空字符串文字,并且您的实际日期如帖子中所述,您需要使用HH而不是hh来解析24小时制中的小时数.您还需要在格式字符串中添加.S,以解析时间字符串的最后一个零:

Assuming that you have just put an empty string literal in the post by mistake and your actual dates are as described in your post, you need to use HH instead of hh to parse hours in 24-hour system. You also need to add .S to your format string to parse the last zero of your time string:

NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-dd-MM HH:mm:ss.S"];
//                 here -------^^       ^------ and here
NSDate *date1 = [df dateFromString:@"2012-12-08 17:00:00.0"];
NSLog(@"%@",date1);

这将产生预期的输出(小时数的差异是由于时区的差异所致):

This produces the expected output (the difference in the hours is due to timezone difference):

2012-08-12 21:00:00 +0000

这篇关于Dateformatter从字符串获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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