简体   繁体   中英

Handling Daylight Savings Using PHP

I am making a website in Wordpress which needs to handle Daylight Savings Time effectively. I have made two PHP functions one to store Local user time as UTC on server, db and another to convert server UTC time to Local User time for display.

They are as follows:-

//display saved UTC dates to Local user time

function ServerTimeToLocal($serverTime){
    $user_id=get_current_user_id();
    $user_timezone = get_user_meta($user_id, "user_timezone", true);

    date_default_timezone_set(SERVER_TZ);   
    $utc_start_stamp = strtotime($serverTime);

    date_default_timezone_set($user_timezone );

    $whichday_local =  date("D", $utc_start_stamp);
    $start_time_local =  date("h:i A", $utc_start_stamp);

    return array("day"=>$whichday_local, "time"=>$start_time_local);
}

//store local user time as UTC on server
function LocalTimeToServer($localTime){
    $user_id=get_current_user_id();
    $user_timezone = get_user_meta($user_id, "user_timezone", true);

            //store timings by local time
    date_default_timezone_set($user_timezone );

    $start_timestamp = strtotime($localTime);
            //convert to server timezone
    date_default_timezone_set(SERVER_TZ);

            //echo $whichday." ".$start_time." ";

    $whichday_server = date("D", $start_timestamp);
    $start_time_server =  date("h:i A", $start_timestamp);
    return array("day"=>$whichday_server, "time"=>$start_time_server);  
}

Although I know that date('I') is used to determine whether Daylight savings time(DST) is in effect, how do I factor in DST into my functions?

Thanks

I usually handle DST like so...

if( date('I') != 1 )
{
    return date('Y-m-d H:i:s', ( time() + 3600 ));
}

return date('Y-m-d H:i:s');

This will check if daylight savings time is in effect, if it is then it will return the date, and add on the hour. If not, it will just return the date.

I have this wrapped in a function getDate(). Comes in really handy

Since you noted WordPress, you should be using WordPress' native functions to do this instead of writing your own.

For example, instead of your ServerTimeToLocal() use get_gmt_from_date() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM