News Tutorials Projects Reviews Authors Contact Search Links Admin
 

Date and Time : Adding Time

Adding Subtracting dates and times.. read the following examples to see where I'm heading with this.

Timezone Example

Say we have a user in America, and another in Russia. They're both reading the same document. However, the time says 'Posted on December the 6th 2002, 11:33am'. Thing is, its only 5am in the morning for the American, and already 4pm in the afternoon for the Russian.. even tho the topic was just posted.

The reason, quite obviously, is that these people are in different timezones.

If this document was on a secure site, or at least a place where you had to sign in.. under member details you could have an option 'Time Zone'. timezone is a value of -12 -> 0 -> + 12. This timezone can then be used to offset the post time of the document for each individual. To do this, we need to add and subtract the times.

Using MySQL, the last edit date of the doucment is being returned as a UNIX Timestamp, and the timezone is being pulled out of the member database as an interger.
$date = $document['lastedit_date'];
$timezone = $member['timezone'];

Using this function, you can deal with such a situation.
function offset_time($st, $timezone=0, $date_format='jS M, g:i a') {
    $serverGMT_offset = -8;
    if(!$st || $st == 0) {
        $st = mktime (date("H")+date("I"), date("i"), 0, date("m"), date("d"), date("Y"));
    }
    $new_time = mktime ( date("H", $st)+date("I", $st)+$timezone+$serverGMT_offset, date("i", $st), 0, date("m", $st), date("d", $st), date("Y", $st));
    return date($date_format, $new_time)."n";
}

You'd call this function using:
$output_date = offset_time($date, $timezone);

A little note about whats going on;
$st is the UNIX Timestamp that will be used. If it not set (or 0) the current time will be used.
$timezone is the timezone offset of the user, in hours.
$date_format can be specified to return a different date format. If its not set, then it'll default to to one set by the function. See the date() function for more details on formatting choices.

The $serverGMT_offset is used to offset the server time to GTM. For example, this server is based in HongKong, so it is eight hours ahead of GMT.. so I use -8 to set this to GMT.

 


Author: Markavian
Last edited on: 8th Dec, 12:50 am
Please rate this article.

« Prev page 'MySQL Data and Time' «

tutorial Pages