How to convert string data into date format in ios?

3.2k Views Asked by At

In my app, i am taking date and time in to string " 2013-06-11 10:15:00 +0000 " like this, but how can i convert this string into date format. I tried like below code but i am getting error in converting.

NSString *string=@"03-05-2014";

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:string];

Would you please help me in this problem?

3

There are 3 best solutions below

0
Prateek Prem On

Try to do this:

NSDateFormatter* f = [[[NSDateFormatter alloc] init] autorelease];
[f setDateFormat:@"yyyy-MM-dd hh:mm:ss"];

NSDate *dateFromString = [f dateFromString:string];

You have to set the same date format in which the (string or date)contains, otherwise the date is returned by NSDateFormatter will be nil.

0
Denny On

You can Use NSCalender Like this.....

NSCalendar *currentCalendar = [NSCalendar currentCalendar];

Refer This Link : Here

2
the1pawan On
NSString *urDateString=@"2013-06-11 10:15:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strDate = [urDateString stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
NSDate *dateString = [dateFormatter dateFromString:strDate];
[dateFormatter setDateFormat:@"MM-DD-yyyy"];
NSString *formattedDateString = [dateFormatter stringFromDate:dateString];
NSLog(@"%@",formattedDateString);