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.

回答1:

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


回答2:

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];


回答3:

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



回答4:

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];