Dealing with dates and times can often be a real headache in the planet of dynamic web development. Your MySQL database has day and time data types that may be extremely powerful – and they must be utilized. Using MySQL in this way makes making date comparisons in your SQL queries a cinch. Nevertheless, often times a developer should convert that data after it’s been retrieved in the database when using these data types within their tables. Mostly, simply storing a date or even time in your database in this way and not doing anything by using it prior to it being utilized by your web application will not have the desired result or structure.
Thankfully, PHP really is really handy here. PHP has this particular built-in function, strtotime (), that converts the provided date right into a UNIX timestamp, which is simply a ten digit number representing the amount of seconds that have elapsed since 00: 00: 00 UTC upon January 1, 1970. This function is very useful and it will work even though the date is prior in order to January 1st, 1970 (you’ll obtain a negative number).
The code below requires a MySQL datetime and converts it right into a UNIX timestamp.
$theDate = “1992-12-31 twenty three: 59: 59”;
$theDateTimestamp = strtotime($theDate);
replicate $theDateTimestamp;
// outputs “725871599”
Once we have a timestamp we can do numerous cool, meaningful things with it – such as finding the quantity of time that has elapsed in between two timestamps. You could do that with two dynamic timestamps, like calculating age difference between two of your own website’s users. You can also do that calculation between a dynamic date and also the current time. I calculate the time which has elapsed between a dynamic day and the current time a great deal, and I’ll show you some code which will make it easy for a person.
This first bit of PHP may be the function I use to do the particular calculation. I tend to keep this function inside a separate file and include this within my code when required. Feel free to use it while you like.
function getElapsedTime($timestamp)
{
$difference = time()-$timestamp;
$difference_days = floor($difference/60/60/24);
$difference -= $difference_days*60*60*24;
$difference_hours = floor($difference/60/60);
$difference -= $difference_hours*60*60;
$difference_minutes = floor($difference/60);
$difference -= $difference_minutes*60;
$difference_seconds = $difference;
if ($difference_days > 0)
{
return $difference_days.’days ‘.
$difference_hours.’hours ‘.
$difference_minutes.’minutes’.
$difference_seconds.’seconds ago’;
}
else
{
return $difference_hours.’hours ‘.
$difference_minutes.’minutes’.
$difference_seconds.’seconds ago’;
}
}
After you have the function included in your own script, all it takes is a little PHP and you’ve got a formatted
calculation of the passed time.
$theElapsedTime = getElapsedTime ($theDateTimestamp);
replicate $theElapsedTime;
//
outputs something like “31 days 6 hours quarter-hour 45 seconds ago”.