Link to home
Start Free TrialLog in
Avatar of DrZork101
DrZork101

asked on

Converting dd/mm/yyyy string into a unix timestamp

Hi,

I have dates stored in my database as strings in the format:

dd/mm/yyyy

and i want to convert them to a unix timestamp when I pull them out of the database so that I can sort them by date.

(when i use sort on the original string it seems to treat it as a nuber e.g. 20/05/1985 as 20051985)

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Cornelia Yoder
Cornelia Yoder
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hello,

this should work:

$date = '20/05/1985';
list($d, $m, $y) = explode('/', $date);
echo mktime(0, 0, 0, $m, $d, $y);

Anyway, consider storing dates as 'date' in mysql table so that you can order directly in query.

Regards
In data base storage, you should use a DATE or DATETIME data type.  These use the ISO 8601 date format which looks (more or less) like YYYY-MM-DD HH:MM:SS.

The ISO format lets you sort the dates.  It also lets you use strtotime() to get UNIX timestamps from the dates or parts of the dates without the overhead of mktime().  This means it is easy to do date-related calculations.

Using a combination of date() and strtotime() you will find that your life gets much easier fast!  So I vote with YoderCM on the approach - refactor the database to incorporate the correct data type.  More information is available here:
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

HTH, ~Ray