Dateformatter to get Date From String

2020-04-19 23:54发布

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..

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.

4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-04-19 23:57

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
查看更多
该账号已被封号
3楼-- · 2020-04-20 00:02

There is a duration gap after seconds, and also you had missed strDate in dateformatter input.

NSString *strDate = @"2012-12-08 17:00:00.0";
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-dd-MM hh:mm:ss.S"]; 
NSDate *date = [df dateFromString:strDate];// formatter format
NSLog(@"%@ %@",date);
[df release];
查看更多
等我变得足够好
4楼-- · 2020-04-20 00:08
NSDateFormatter *dateformat=[[NSDateFormatter alloc]init];
[dateformat setDateFormat:@"dd/MM/yyyy hh:mm:ss"];
NSDate *today = [NSDate date];
NSString *currentDate=[dateformat stringFromDate:today];
NSLog(@"PrintToday Date is %@ ",currentDate);

NSDate *date1 = [df dateFromString:@""];

you need to pass string in the your above line

查看更多
老娘就宠你
5楼-- · 2020-04-20 00:19

Do this:

NSString *strDate = @"2012-12-08 17:00:00.0";
NSDateFormatter *df=[[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-dd-MM HH:mm:ss.S"]; 
NSDate *date1 = [df dateFromString:strDate];// forgot to add valid string for according to date formatter format
NSLog(@"%@",date1);
[df release];
查看更多
登录 后发表回答