Ở đây tôi sử dụng hàm này để chuyển đổi datetime thành múi giờ khác. Để có kết quả tốt nhất nếu bạn chuyển đổi datetime của bạn thành múi giờ utc và sau đó chuyển đổi thành múi giờ yêu cầu thì đó là kết quả tốt hơn cho nó.
function ConvertTimezoneToAnotherTimezone($time, $currentTimezone, $timezoneRequired) {
$dayLightFlag = false;
$dayLgtSecCurrent = $dayLgtSecReq = 0;
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d H:i:s");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecCurrent = -3600;
// }
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s ");
$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d H:i:s ");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecReq = +3600;
// }
date_default_timezone_set($system_timezone);
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
if ($dayLightFlag) {
$final_diff = $dayLgtSecCurrent + $dayLgtSecReq;
$date->modify("$final_diff seconds");
}
$timestamp = $date->format("Y-m-d H:i:s ");
return $timestamp;
}
Cảm ơn bạn.
đánh bại tôi đến đấm, xóa tôi. Điều đáng nói đến là DateTime có sẵn từ PHP 5.2 - có bản vá cho 5.1 nhưng nó là thử nghiệm –
Yep. datetime là khá "mới". Ngay cả trong 5.2 nó không chứa tất cả các chức năng cần thiết, mong muốn và được đề cập trong hướng dẫn sử dụng – ITroubs
Câu trả lời hay. Các chức năng này cũng tự động xử lý việc tiết kiệm ánh sáng ban ngày, ở đây chỉ cần thêm một khoảng bù là clunky và không chính xác. –