Behind the veil of Colorado's premier Interactive Agency

strtotime <3 Ryan Hadley

August 29th, 2008

This is a love story for a php built in function.  strtotime().  I’m sure other languages/frameworks have a similar function, but I’m mostly familiar with php.

Here is an example of it’s coolness:

echo date(”m/d/Y h:i:s”, strtotime(’last week’)) . “\n”;

08/22/2008 09:12:18

Or how about:

echo date(”m/d/Y h:i:s”, strtotime(’next tuesday’)) . “\n”;

09/02/2008 12:00:00

It follows the Gnu Date Input Formats as seen here.  As you can see, it recognizes many formats of time, and fuzzy time values like “next”, “this”, “last”, “tomorrow”, “yesterday”.  Extremely handy.

But… It can’t parse srings like “first day of last month”.  This is not hard to accomplish though, with another great function, mktime.

echo date(”m/d/Y h:i:s”, mktime(0, 0, 0, date(’m') – 1, 1)) . “\n”;

07/01/2008 12:00:00

And, the last day of next month is just as easy:

echo date(”m/d/Y h:i:s”, mktime(0, 0, 0, date(’m') + 1, date(’t', strtotime(’next month’)))) . “\n”;

09/30/2008 12:00:00

Also, with using mktime with + and -, you don’t even have to worry about things like rolling back from 1/1/2008 to 12/31/2007.  It’ll handle that for you.  It knows that January minus 1 is December of last year.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • Reddit
  • Slashdot
  • del.icio.us
  • StumbleUpon
  • Netvouz
  • ThisNext
  1. One Response to “strtotime <3”

  2. By Jasper Showers on Nov 24, 2008 | Reply

    What a beautiful love story! I teared up a little…

Post a Comment