Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting date format in Objective-C

I need to set format like this: 7 Aug 2015 14:42:11

Here is my code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *string = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date Current :- %@",string);
like image 300
ios Avatar asked Aug 07 '15 10:08

ios


2 Answers

You get 7 Aug 2015 14:42:11, if you use this code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"dd MMM YYYY HH:mm:ss";
NSString *string = [formatter stringFromDate:[NSDate date]];
NSLog(@"Date Current :- %@",string);

Your mistake is incorrect date format,

@"yyyy-MM-dd HH:mm:ss" should be this: @"dd MMM YYYY HH:mm:ss"

like image 122
Dharmesh Dhorajiya Avatar answered Nov 02 '22 23:11

Dharmesh Dhorajiya


Try this

NSString myString = @"2012-11-22 10:19:04";
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";     
NSDate *yourDate = [dateFormatter dateFromString:myString];
dateFormatter.dateFormat = @"dd-MMM-yyyy";
NSLog(@"%@",[dateFormatter stringFromDate:yourDate]);

Hope it helps.

like image 30
Pradumna Patil Avatar answered Nov 02 '22 23:11

Pradumna Patil