简体   繁体   中英

Daylight Saving Time (DST) in CakePHP

I'm creating a web application using cakephp 1.2.6. There is a functionality that I need to save the time that user is entered in GMT format. I'm using below method to do this.

function convertDateTimeToGMT($dateTimeStr,$fromTimeZone, $format = 'Y-m-d H:i:s') {
    if (empty($dateTimeStr))
    return $dateTimeStr;
    else if (empty($fromTimeZone))
    return $dateTimeStr;
    else {
        // Inverse the + or minus. Decimal value should be passed
        //$timeHelper = new TimeHelper();
        $newTZ = -1 * $fromTimeZone;
        return $this->format($format, $dateTimeStr, null, $newTZ) ;
    }
}


function format($format = 'd-m-Y', $date, $invalid = false, $userOffset = null) {
    $date = $this->fromString($date, $userOffset);
    if ($date === false && $invalid !== false) {
        return $invalid;
    }
    return date($format, $date);
}

function fromString($dateString, $userOffset = null) {
    if (empty($dateString)) {
        return false;
    }
    if (is_int($dateString) || is_numeric($dateString)) {
        $date = intval($dateString);
    } else {
        $date = strtotime($dateString);
    }
    if ($userOffset !== null) {
        return $this->convert($date, $userOffset);
    }
    return $date;
}

function convert($serverTime, $userOffset) {
    $serverOffset = $this->serverOffset();
    $gmtTime = $serverTime - $serverOffset;
    $userTime = $gmtTime + $userOffset * (60*60);
    return $userTime;
}

convertDateTimeToGMT($dateTimeStr,$fromTimeZone, $format = 'Ymd H:i:s') is the method that I'm calling in my code to pass the date time and time zone. I have a combo box of time zones and if user select time zone as "Pacific" it will pass the -8 as the value of $fromTimeZone . But because of the DST this can be changed.

So is there any way in cakephp to find the up to date time zone values automatically and convert the time to GMT?

Once you know the timezone of the user you can get its offset as follows:

$est_tz = new DateTimeZone('America/New_York');
$d = new DateTime("now", $est_tz);
$offset = $est_tz->getOffset($d);

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