views:

36

answers:

3

Is there an equivalent (or vaguely similar) to PHP's strtotime in Objective C/iPhone?

strtotime can for example understand the below time expressions (from the php documentation):

  • echo strtotime("now"), "\n";
  • echo strtotime("10 September 2000"), "\n";
  • echo strtotime("+1 day"), "\n";
  • echo strtotime("+1 week"), "\n";
  • echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
  • echo strtotime("next Thursday"), "\n";
  • echo strtotime("last Monday"), "\n";
+1  A: 

[NSDate +dateWithString] does what you want, I think.

Michael Aaron Safyan
A: 

Here is some code for the first and second of your queries:

  • echo strtotime("now"), "\n";
  • echo strtotime("10 September 2000"), "\n";
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    [format setDateFormat:@"dd MMM yyyy"];
    NSDate *now = [[NSDate alloc] init];
    NSString *dateString = [format stringFromDate:now];
    NSLog(@"The time: %@", dateString);

    NSDate *parsed = [format dateFromString:@"10 Sep 2000"];
    NSLog(@"The time: %@", [format stringFromDate:parsed]);

Obviously the alloc-ed objects need releasing.

And here's an article that may help with the others:

http://www.drobnik.com/touch/2009/05/adding-days-to-nsdate

Matt
I think you as well as Michael missed the point, because you should not need to know the input format (this is the design of strtime).Simply I guess the answer is "there is no equivalent".
Jonny
Well Objective-C isn't a scripting language like PHP so it can't do what you want it to do.The answer is - there is an equivalent but it's a statically typed equivalent and it's a bit more verbose.
Matt
A: 

All of a sudden I remembered the "PHPJS" project. There is a javascript port of strtotime here:

http://phpjs.org/functions/strtotime:554

I have yet to test it (which means, porting it to a Objective C function or similar), so I'm not sure how well it actually performs in comparison with the original strtotime. Might have time for checking that later...

Jonny