Diffy
Diffy

Reputation: 735

NSString to NSDate keeps getting null

I know this been asked for so many times but I always end up getting null in my NSDate. I have a string like this "January 16, 2012 21:44:56" I want to convert it to "January 16, 2012 09:44:56 PM". I want to add a PM in the converted date and convert the 24 hour time format to 12 hour time format. Here's my code.

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMMM dd, YYYY HH:ii:ss a"];

    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:dateString];

Upvotes: 1

Views: 1619

Answers (5)

rckoenes
rckoenes

Reputation: 69469

There is an error in your format string an also you need to tell the formatter the Locale in which your date string is presented.

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
[dateFormatter setDateFormat:@"MMMM dd, yyyy HH:mm:ss a"];

NSDate *dateFromString = [dateFormatter dateFromString:dateString];
[dateFormatter release], dateFormatter = nil;

Setting the Local is very important since you have an name of a date in your input. You will need to tell the NSDateFormatter is wich language the name will be. In the example given it is in english. I've you run you code without setting the local on a device where the language is not set to english it wil fail to parse the date.

Upvotes: 2

Shanti K
Shanti K

Reputation: 2918

As Ali3n correctly pointed out, you should first set the format of dateString to the formatter to get a valid date object. Next you should set the formatter's format to the desired one and continue. Do the following:

NSString *dateString = @"January 16, 2012 21:44:56";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, yyyy HH:mm:ss"];

NSDate *dateFromString;
dateFromString = [dateFormatter dateFromString:dateString];

[dateFormatter setDateFormat:@"MMMM dd, YYYY HH:mm:ss a"];
NSString *stringFromDate  = [dateFormatter stringFromDate:dateFromString];

Upvotes: 2

Anil Kothari
Anil Kothari

Reputation: 7733

As for your requirements you have to change the dateFormatter.Check this link for more.

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MMMM dd, YYYY hh:mm:ss a"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate date]];
[dateFormatter release];
NSLog(@"%@",dateString);

Upvotes: 0

user971401
user971401

Reputation:

Try to escape literals in the format string.

[dateFormatter setDateFormat:@"MMMM dd',' YYYY HH:ii:ss a"];

Upvotes: 1

Ali3n
Ali3n

Reputation: 1244

@"MMMM dd, YYYY HH:ii:ss a" this format should match with the date the ypu are passing to the date formatter ..

Upvotes: 2

Related Questions