ios
ios

Reputation: 975

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

Upvotes: 5

Views: 5775

Answers (4)

Dharmesh Dhorajiya
Dharmesh Dhorajiya

Reputation: 3984

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"

Upvotes: 3

RMDeveloper
RMDeveloper

Reputation: 477

Add this method to your utility class and pass the date whatever you want to convert

+(NSString *)dateToString:(NSDate *)date
{
    NSDateFormatter *dateFormat =[[NSDateFormatter alloc]init];
    [dateFormat setDateFormat:@"dd MM yyyy HH:mm:ss"];
    return [dateFormat stringFromDate:date];
}

Upvotes: 0

Anbu.Karthik
Anbu.Karthik

Reputation: 82759

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

//Date Current :- 7 Aug, 2015 16:29:48

the output

enter image description here

Upvotes: 1

Pradumna Patil
Pradumna Patil

Reputation: 2220

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.

Upvotes: 1

Related Questions