European Dates and Strtotime
There is this magic PHP function called strtotime which converts your date to a timestamp measured from 1 Jan 1970. This makes sorting and manipulating arrays with dates a doddle. But only if you are in America, it’s a pain in the bum for the rest of the world.
And I’ll tell you why…
US Date formats
For some strange reason in the USA they format their dates: Month – Day – Year. It’s most bizarre and totally illogical. But it does mean if you have a form with a date field then it expects the date to be entered as MM/DD/YYYY or Mmm/DD/YY or some equivalent combination.
Everybody else in the World
The rest of the world uses the traditional and more logical DD/MM/YYYY format. If you enter a date as DD/MM/YYYY and convert to strtotime then convert back you get MM/DD/YYYY. Which is no good at all.
It’s pretty easy:
<?php $date = '8/6/2013'; $timestamp = strtotime($date); echo $timestamp; ?>
This will return ‘ 1375747200’ which represents 6 August 2013. But this is no good outside the USA where we all think the date is 8 June 2013.
Fixing the problem
There are all sorts of workarounds that will take a Non-US format and convert it into US format so you can use strtotime but they are all a bit flaky and not that easy to use.
However I have found a dinky feature of strtotime that solves many of the issues. If you format your date as DD.MM.YYYY (note the periods not slashes) then strtotime recognises this as a non-US date and converts it correctly:
<?php $date = '8.6.2013'; $timestamp = strtotime($date); echo $timestamp; ?>
This will return ‘1370649600’ which represents 8 June 2013.
And if you use YYYY-MM-DD it will assume ISO 8601 format.
How you get the date in the first place is up to you. I let the the visitor uses slashes and replace them with periods before converting to a timestamp:
<?php $date = '8/6/2013'; $date = str_replace('/' , '.' , $date); $timestamp = strtotime($date); echo $timestamp; ?>
So to recap:
Slashes assumes US formatted dates.
Periods assumes Non-US Dates.
Hyphen assumes ISO 8601 formatted dates.
Much simpler and dead easy to use/convert/style/process