How to get Unix timestamp in php based on timezone

后端 未结 5 582
温柔的废话
温柔的废话 2020-11-30 07:54

Code first

    echo time() . \'
\'; echo date(\'Y-m-d H:i:s\') . \'
\'; date_default_timezone_set(\'America/New_York\'); echo time() .
5条回答
  •  难免孤独
    2020-11-30 08:28

    Here is a function to convert unix/gmt/utc timestamp to required timezone.

    function unix_to_local($timestamp, $timezone){
        // Create datetime object with desired timezone
        $local_timezone = new DateTimeZone($timezone);
        $date_time = new DateTime('now', $local_timezone);
        $offset = $date_time->format('P'); // + 05:00
    
        // Convert offset to number of hours
        $offset = explode(':', $offset);
        if($offset[1] == 00){ $offset2 = ''; }
        if($offset[1] == 30){ $offset2 = .5; }
        if($offset[1] == 45){ $offset2 = .75; }
        $hours = $offset[0].$offset2 + 0;
    
        // Convert hours to seconds
        $seconds = $hours * 3600;
    
        // Add/Subtract number of seconds from given unix/gmt/utc timestamp
        $result = floor( $timestamp + $seconds );
    
        return $result;
    }
    

提交回复
热议问题