Practical Date/Time examples with PHP and MySQL - How old are you? (exactly)
(Page 3 of 6 )
Using the date_diff() function that we’ve just created it's very easy to calculate your exact age by how many years, days, hours, minutes and seconds since you were born:
<?php
// Calculating my exact age
$str_birthday = "1978-04-26"; // My Birth Day
$str_today = date("Y-m-d H:i:s"); // The exact time
date_diff($str_birthday, $str_today);
?> As you see I’m using the same function but changing the parameters a little. First $str_birthday is a fixed string, in this example my birthday.
You can, for example, ask the user through a form and then call the function like this:
<?php date_diff($_POST[‘birthday’], date("Y-m-d H:i:s")); ?> The trick here is the date() function. With its given parameters prints the exact date of today in the format YYYY-MM-DD hh:mm:ss.
The code returns:
9024 days, 17 hours, 29 minutes, 57 seconds
How many days until…? Again, using the same function that we created at the beginning and changing the parameters appropriately we can calculate how many days until a given date. There is a problem though; the UNIX timestamp only works for dates between January 1st, 1970 and December 31st, 2037. Dates outside that range will give an unpredictable result.
Now, hoping that we'll come up with a solution for this in the next thirty years let's do the math:
<?php
$str_future_date = "2028-04-26"; // I'll be fifty this day!
date_diff(date("Y-m-d H:i:s"), $str_future_date);
?> At this point you should be familiar with the function, just tweaking the parametersa little. In this case the first parameter is the exact date of today and the second is the future date that we want to know how many days until.
Next: Dates with MySQL >>
More MySQL Articles
More By Mauricio Cuenca