What do you do when your website is hosted on a server whose time is wrong, by an hour, by a minute, or even by a few seconds (if the seconds bother you..)? Or what if your host is just in a different time zone, and you want all date() queries to be returned in YOUR time zone, not theirs?
All you need to do is use this replacement for date(). I recommend putting it in a time.php file, and then including that file in all of your scripts. Any time you would make a call to date(), make a call to time_Date() instead. The calling syntax is exactly the same as date(), so if you want to make a transition from date() to time_Date() in all of your code, all you need to do is do a replace of "date(" with "time_Date(" in all of your files.
Whenever you need to change the time offset, just hard-code the $time_offset value in the function, and voila, all of your date/time queries will reflect the change. Just as you would with date(), you can also send in a timestamp as the second argument, and it will return the date/time for that timestamp (without offsetting it, obviously).
Optional: If you want to make the time offset dynamic (example: for the user to choose a time zone), you can also easily modify the code to meet those needs as well (I would recommend having a separate function if you choose to do that, though, and have that function make a call to this function, that way you can still use this function to correct the server time).
Code: Select all
function time_Date($format, $timestamp=false)
{ // this function should be used in all cases where date() would otherwise be used
// Time offests are important if the server's time (or time zone) is wrong.
$time_offset = 0; // setting for a perfect server (one that doesn't actually need this function). Change the 0 to a different value, depending on how wrong the server's time is. This is measured in seconds, not minutes/hours.
// Examples:
// Change 0 to -21600 for a server which is 6 hours too fast
// Change 0 to 3600 for a server which is an hour too slow
// Change 0 to -1800 for a server which is half an hour too fast
if ($timestamp == false) // if timestamp is not passed..
return date("$format", date("U") + $time_offset);
else
return date("$format", $timestamp);
}