A hidden gem in PHP
Added on: Friday 20th February 2009
One of the most common tasks when developing websites or online applications is date manipulation. You might for example need to create a list of memberships due to expire within the next month.
Of course PHP has plenty of date/time manipulation functions you can use but there is one called strtotime (string to time) that is very underrated.
The description in the manual says - Parse about any English textual datetime description into a Unix timestamp
A timestamp is simply a numeric representation of a date and it is this value that can be used to compare two dates or add a number of days, weeks, years etc.
I have been using strtotime for years but up until recently it was mainly to convert dates pulled from a database (as they are retrieved as strings).
If I wanted to work out the date in a months time I would use mktime. For example:
$dt = mktime(0,0,0,date("m")+1,date("d"), date("Y"));
This is not too complicated but it still has three other function calls (to date()) within it.
Consider however this alternative:
$dt = strtotime("next month");
A bit simpler, eh?
As the description says you can use just about any English textual datetime description. I tracked down a reference giving some information on the date input formats but essentially you can use common phrases such as 'Monday', 'next week', 'last year', '1 month', '1 day ago'.
By default the function calculates the timestamp from the current date and time but you can also include as a second parameter a timestamp from which to calculate the new date from.
I discovered this whilst looking for an easy way for users to add tasks to our contact management software. I wanted a way for people who were away from their office to be able to add a task or reminder by email from their Blackberry or iPhone.
This had to be as simple as possible - the email is sent to a specific address with the due date of the task or reminder in the subject and the details in the subject.
I thought a nice touch would be to allow users to put tomorrow or next friday in the subject and I thought I'd have to write a function to process these into dates - but then I discovered that it was already done. Fantastic!