Sasi
Sasi

Reputation: 1897

Dateformatter to get Date From String

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.

Upvotes: 1

Views: 2040

Answers (4)

Ankit Thakur
Ankit Thakur

Reputation: 4749

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

Upvotes: 1

Paresh Navadiya
Paresh Navadiya

Reputation: 38239

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

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

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

Upvotes: 1

Pandey_Laxman
Pandey_Laxman

Reputation: 3908

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

Upvotes: 0

Related Questions