bengoerz Posted April 7, 2007 Share Posted April 7, 2007 I recently needed to display a user's age by calculating from a MySQL datestamp. Because my users could be older than a unix timestamp can function, using mktime() was not an option. I did not find a quick solution online, so I created the following: // Convert date of birth to age // Pull Date of Birth from MySQL // For demonstration, this is defaulted to Dec 7, 1941 $dob = "1941-12-07"; // Create current datestamp in YYYY-MM-DD format $today = date("Y-m-d", time()); // Subtract birth year from current year, -1 for partial first year $age = substr($today, 0, 4) - substr($dob, 0, 4) - 1; // If birthday this year has past, add 1 to age $thisMMDD = (substr($today, 5, 2).substr($today, 8, 2)); $birthMMDD = (substr($dob, 5, 2).substr($dob, 8, 2)); if($thisMMDD > $birthMMDD){ $age++; } // Output age echo $age; This works, but would anyone like to offer a more elegant solution? Link to comment https://forums.phpfreaks.com/topic/45987-mysql-datestamp-comparison-without-mktime/ Share on other sites More sharing options...
Barand Posted April 7, 2007 Share Posted April 7, 2007 If you formatted the dates with 'Ymd' instead of 'Y-m-d' you only need 1 substr() for 'mmdd' Also you can do it with timestamp values <?php $dob = strtotime("1941-12-07"); // later versions of php handle negative timestamps $age = date('Y') - date('Y', $dob) - 1; if (date('md') > date('md', $dob) ) $age++; echo $age; ?> --> 65 Link to comment https://forums.phpfreaks.com/topic/45987-mysql-datestamp-comparison-without-mktime/#findComment-223479 Share on other sites More sharing options...
bengoerz Posted April 7, 2007 Author Share Posted April 7, 2007 Thanks for the great solution. Unfortunately, it doesn't do me any good because I am on a little earlier version of PHP. But I'm sure others can use it. From the date() manual: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). Link to comment https://forums.phpfreaks.com/topic/45987-mysql-datestamp-comparison-without-mktime/#findComment-223531 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.