mayuur
mayuur

Reputation: 4746

dateFromString returns nil

This is my NSString,

myDate : 2011-06-07 11:23:47  0000

And this is the code,

NSTimeZone *currentDateTimeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *currentDateFormat = [[NSDateFormatter alloc]init];
[currentDateFormat setTimeZone:currentDateTimeZone];
[currentDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *tempDate = [currentDateFormat dateFromString:second];

Still tempDate gets the value nil.
Can anyone help?

Upvotes: 5

Views: 5507

Answers (4)

Zahur
Zahur

Reputation: 181

What I think is, it not related to TimeZone but the device 24hours settings. Developer has to check if the device timings are of 24hours then they should use HH, and if the device timings are of 12hours then they should use hh.

Upvotes: 1

Sujal
Sujal

Reputation: 1205

Try this, This is the function to get Date from String .

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setFormatterBehavior:NSDateFormatterBehavior10_4];
[df setDateFormat:@"EEE, dd MMM yy HH:mm:ss"];
NSDate *convertedDate = [df dateFromString:stringDate];
[df release];
// [convertedDate description]
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setAMSymbol:@"AM"];
[formatter setPMSymbol:@"PM"];
[formatter setDateFormat:@"MM/dd/yyyy hh:mm:a"];
return [formatter stringFromDate:convertedDate];

Upvotes: 2

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

How did you get the date string? It needs to be 2011-06-07 11:23:47 +0000 for this to work.

Upvotes: 3

Viktor Apoyan
Viktor Apoyan

Reputation: 10755

NSTimeZone *currentDateTimeZone = [NSTimeZone defaultTimeZone];
NSDateFormatter *currentDateFormat = [[[NSDateFormatter alloc]init] *autorelease*];
[currentDateFormat setTimeZone:currentDateTimeZone];
[currentDateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss *ZZZZ*"];
NSDate *tempDate = [currentDateFormat dateFromString:second];

Add autorelease and ZZZZ insead of Z.

Upvotes: 0

Related Questions