Iqbal Khan
Iqbal Khan

Reputation: 4617

Creating NSDate from month, day and year

I want to create a NSDate variable from a string, that date is coming from third party server so i cannot change it. the date is in this format December 08, 2013 and i am using given below date formater style to convert it into date but that is creating a wrong and fixed date for all items which is 2012-12-22 19:00:00 +0000

Will you please guide me how to solve this problem. i donot want break string and use NSDateComponents to create date.

[dateFormaterForSermonTemp setDateFormat:@"MMMM dd, YYYY"];

Upvotes: 1

Views: 2454

Answers (4)

Jordan Montel
Jordan Montel

Reputation: 8247

You can use the following code :

NSString *stringDate = @"December 08, 2013";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM dd, yyyy"];
NSDate *date = [dateFormat dateFromString:stringDate];

// Convert date object to desired output format
[dateFormat setDateFormat:@"MMMM dd, yyyy"];
stringDate = [dateFormat stringFromDate:date];

NSLog(@"%@", stringDate);

stringDate is the string from your server, you convert it to a NSDate and you add a new format for the date like @"MMMM dd, yyyy".

(Here, you will have the same result but change the format like @"MMMM-dd-yyyy EEE" for example to get another format date).

EDIT :

Maybe you need to set the timeZome for your date

[dateFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:00"]];

Upvotes: 5

Sandeep Ahuja
Sandeep Ahuja

Reputation: 931

NSString *strDate=@"December 08, 2013";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

NSDate *date=[dateFormatter dateFromString:strDate];

Try this...

Upvotes: 0

Marek R
Marek R

Reputation: 37607

Here you have documentation about date format string. (the rod not the fish).

So your format string for date December 08, 2013 should be something like (the fish):

@"MMMM dd, y"

and don't forget to set proper locale for the date formater or you can have unexpected problems on devices with different locale settings.

Upvotes: 0

Suhit Patil
Suhit Patil

Reputation: 12023

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM dd, yyyy"];
NSDate *date = [dateFormat dateFromString:@"December 08, 2013"];

Upvotes: 0

Related Questions