tags:

views:

219

answers:

2

I want to convert this ,

NSString *result1=@"Mon, 28 Sep 2009 06:35:42 PDT";

to nsdate using NSDateFormatter in iphone....

Can anyone help me?

Thanks in advance.....

A: 

That's what I do in my program:

NSString *dateString = @"Mon, 28 Sep 2009 06:35:42 PDT";

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

I'm using medium style, but there are more styles, you probably should use kCFDateFormatterLongStyle or kCFDateFormatterFullStyle, and then:

NSDate *aDate = [newFormatter dateFromString: dateString];
[newFormatter   release];

Hope this helps

Nava Carmon
I am using this format[dateFormat setDateFormat:@"MMM dd,yyyy HH:mm:ss aaa"];But aDate returns nil.
This example indeed returns nil for aDate, even with kCFDateFormatterFullStyle.
nall
Well, I'm using shorter format. Sorry it didn't work for you. Try another interface [newFormatter initWithDateFormat:@"MMM dd,yyyy HH:mm:ss aaa"] allowNaturalLanguage:YES]; and then use the dateFromString to get the NSDate.
Nava Carmon
Above line convert string to nsdate.. But again i want to convert nsdate to nsstring .. But it cant do this can u help me?
NSString *dateString = @"Mon, 28 Sep 2009 06:38:42 PDT"; NSDateFormatter *newFormatter = [[NSDateFormatter alloc] initWithDateFormat:@"MMM dd,yyyy HH:mm:ss aaa" allowNaturalLanguage:YES]; NSDate *date=[newFormatter dateFromString:dateString]; NSString *string; string=[newFormatter stringFromDate:date];can you please check this code
yes, this should work. Doesn't it work for you?
Nava Carmon
+1  A: 

I believe you want this:

NSString* dateString = @"Mon, 28 Sep 2009 06:35:42 PDT";

NSDateFormatter* newFormatter = [[[NSDateFormatter alloc] init] autorelease];

// Use this format to parse the string
[newFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss zzz"];
NSDate* aDate = [newFormatter dateFromString:dateString];

// Now change the format to that desired for printing
[newFormatter setDateFormat:@"MMM dd,yyyy HH:mm:ss aaa"];
NSLog(@"%@", [newFormatter stringFromDate:aDate]);

// Result:
// 2009-09-29 23:50:09.440 test[15396:903] Sep 28,2009 06:35:42 AM

You can find these codes here (as referenced in the NSDateFormatter documentation): http://unicode.org/reports/tr35/tr35-6.html#Date%5FFormat%5FPatterns

nall
Can you please check with this format [dateFormat setDateFormat:@"MMM dd,yyyy HH:mm:ss aaa"];its return nil.I want to save my date as this formate...
I updated the code to reflect printing the date in the format you desire.
nall
It's important to make a distinction between the NSDate object and a string representation of it. When you're parsing the string, that format MUST match the string you're parsing. However, once you have an NSDate object, you can then display it any way you see fit (e.g. using the format string you mentioned above)
nall