Changing date and time between timezones

前端 未结 2 1425
[愿得一人]
[愿得一人] 2021-01-21 16:00

I have been trying to convert between timezones a given date and time.
Code speaks more than words, so here it is:

/**
 * Returns the date and time in the n         


        
相关标签:
2条回答
  • 2021-01-21 16:22

    OK, try this instead:

    function changeDateTime($datetime, $input_tz, $output_tz) {
    
        // Return original string if in and out are the same
        if($input_tz == $output_tz) {
            return $datetime;
        }
    
        // Save current timezone setting and set to input timezone
        $original_tz = date_default_timezone_get();
        date_default_timezone_set($input_tz);
    
        // Get Unix timestamp based on input time zone
        $time = strtotime($datetime);
    
        // Start working in output timezone
        date_default_timezone_set($output_tz);
    
        // Calculate result
        $result = date('Y-m-d H:i:s', $time);
    
        // Set timezone correct again
        date_default_timezone_set($original_tz);
    
        // Return result
        return $result;
    
    }
    
    $out = changeDateTime("2012-08-10 11:33:33", 'Europe/London', 'Europe/Madrid');
    var_dump($out);
    

    Rather than messing about doing all that complicated maths, just let PHP do all the hard work for you ;-)

    See it working

    0 讨论(0)
  • 2021-01-21 16:39

    If your stumbling on this, it can be done cleaner now with the DateTime Object.

    public function convertTZ($dateTimeString, $inputTZ, $outputTZ){
        $datetime = 
            \DateTime::createFromFormat('Y-m-d H:i:s', //input format - iso8601
            $dateTimeString, 
            new \DateTimeZone($inputTZ))
            ->setTimezone(new \DateTimeZone('$outputTZ'));
    
        //outputs a string, if you want the dateTime obj - remove ->format
        return $datetime->format('Y-m-d H:i:s'); //output format 
    
    }
    
    0 讨论(0)
提交回复
热议问题