mlogo
Archives

If you have ever developed in PHP, you have likely utilized the amazing strtotime function. It lets you throw any string at the function, and it returns an integer UNIX Epoch timestamp. It’s incredibly flexible. All of the following will return a valid UNIX timestamp:

  • strtotime("Nov 2, 1984");
  • strtotime("Nov 2, 1984 5:34AM");
  • strtotime("Nov 2, 1984 15:34");
  • strtotime("Last Tuesday");
  • strtotime("Tomorrow");

Now that I’m doing some work in Cocoa, I really miss this capability. Thankfully, as every copy of OS X (at least since 10.4) has shipped with /usr/bin/php installed by default, we can call it from Cocoa! Here is some code that will return an NSDate from a string, via PHP’s strtotime();


-(NSDate *) stringToTimeViaPHP:(NSString *)aString
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/bin/php"];

    NSString *strToTimeArgs = [NSString stringWithFormat:@"print strtotime('%@');",aString];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-r",strToTimeArgs, nil];

    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    //NSLog(@"Launching %@ ",[task arguments]);
    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *string;
    string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

    int dateInterval = [string intValue];

    theDateTaken = [NSDate dateWithTimeIntervalSince1970:dateInterval];
    //NSLog(@"The date stands as %@",theDateTaken);

    return theDate;
}

I’ve only tested this on Leopard (Mac OS X 10.5.2), but it should work on Tiger as well. I am releasing this code under the MIT License. Let me know in the comments if you find it useful in your app.

Monday 4/28 around 5 pm  

Leave a Reply