0

I surfed through existant questions regarding this theme, but my issue is little specific and i can't figure out source of the problem.

I have string like:

str = @"Sun Mar 06 13:20:12 2011";

And i want to convert it to NSTimeInterval. Im doing it this way:

NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"ddd mmm dd hh:mm:ss yyyy"];
NSDate *date = [formatter dateFromString:str];

NSTimeInterval interval = [date timeIntervalSince1970];

"date" always gets nil.

I think I'm wrongly defining the format, but can't figure out at what part.

Misha
  • 5,260
  • 6
  • 35
  • 63
  • just as a tip, if you experience string-to-date problems you can get a hint what went wrong when you do the opposite and print it to the console. `NSLog(@"Date: %@", [formatter stringFromDate:[NSDate date]]);` shows you quickly that there must be something wrong with the format. – Matthias Bauch Mar 07 '11 at 12:39

3 Answers3

2

Based on http://www.deanoj.co.uk/ios-development/nsdateformatter-formatting-strings-reference/

you should use ccc MMM dd hh:mm:ss yyyy instead of ddd mmm dd hh:mm:ss yyyy

j_freyre
  • 4,623
  • 2
  • 30
  • 47
  • Fantastic site. And your answer is correct except of there is a need to change hh to HH in addition to ccc. Thanks. – Misha Mar 07 '11 at 13:05
1

Hope this helps

NSDateFormatter dateFromString returns nil

Community
  • 1
  • 1
visakh7
  • 26,380
  • 8
  • 55
  • 69
  • Yep. This helped. Had to change hh to HH in addition to changes provoded in previous answer. Thanks. – Misha Mar 07 '11 at 13:04
0

I always advice you to avoid usage of nsdateformatter. Instead use nsdatecomponents. I have suffered a lot because of its instability. Intially it got fixed after using few properties of NSdateFormatter but I got the nil problem in 4.2.1 version of iOS.

chk this link to understand nsdateformatter better.

http://developer.apple.com/library/ios/#qa/qa2010/qa1480.html

thndrkiss
  • 4,515
  • 8
  • 57
  • 96