iCoder4777
iCoder4777

Reputation: 1692

Converting NSString to NSDate is not working

I've read the DateFormatting guide and I'm still not able to get why my date conversion is not working as per requirement. For example:

NSString *str1 = @"12/20/2013 12:39:55 PM";
NSDateFormatter *dateFo = [[NSDateFormatter alloc] init];

[dateFo setDateFormat:@"MM/dd/YYYY hh:mm:ss a"];
NSDate *serverDate1 = [NSDate date];
serverDate1 = [dateFo dateFromString:str1];

In return I'm getting date as "2013-01-05 07:09:55 +0000". I have tried a lot why NSDate is not returning correct date.

Any help would be appreciated.

Upvotes: 0

Views: 189

Answers (2)

IronManGill
IronManGill

Reputation: 7226

NSString *dateWithInitialFormat = @"12/20/2013 12:39:55 PM";
NSDateFormatter *dateFo = [[NSDateFormatter alloc] init];
[dateFo setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *serverDate1 = [NSDate date];
serverDate1 = [dateFo dateFromString:dateWithInitialFormat];

This will get you your solution

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

Instead of YYYY use yyyy in your dateFormat:.

NSString *str1 = @"12/20/2013 12:39:55 PM";
NSDateFormatter *dateFo = [[NSDateFormatter alloc] init];

[dateFo setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *serverDate1 = [NSDate date];
serverDate1 = [dateFo dateFromString:str1];

Upvotes: 1

Related Questions