我有一个以分钟为单位的UTC偏移量:例如-240
我正在尝试为这个特定的偏移量找到当前当天午夜的相应UNIX时间戳。
我在这样的问题中发现了类似的信息:我如何获得"午夜"的UTC时间;对于给定的时区?
但是,我没有城市名称/时区管辖权,只有一分钟偏移。我认为这应该是好的,因为对于我的目的,我不需要考虑夏令时,它可以关闭一个小时,仍然很好。
抵消:-420
午夜on 7/12/2014: 1405148400 (unix TS)
对于UTC,我必须首先告诉它是TZ的第二天还是同一天,因为它可能有不同的"最后午夜"。
虽然这个解决方案看起来有点丑,但它确实做到了我认为你想要的!本例使用-180分钟作为偏移量。
date_default_timezone_set('UTC');
// Work out which day the time zone is in
$day = strtotime('-180 minutes');
// Strip of the time part of the day, to give UTC midnight on the correct day
$utcMidnight = strtotime('midnight', $day);
// Now apply the offset in reverse to give the zone's midnight
$zoneMidnight = strtotime('+180 minutes', $utcMidnight);
您可以使用date_default_timezone_set
使所有与时间相关的函数都承认偏移。首先要做的是将这些分钟转换成小时,因为UTC的n和n+1之间有1小时的差距。
$hours = $minutes / 60;
我还建议您先检查分钟值:
if($minutes % 60 == 0) // We're good.
现在,如果您想将UTC偏移量转换为时区,您可以创建以下函数:
<?php
function offsetToTimezone($offset){
$timezones = array(
"-12" => "Pacific/Kwajalein",
"-11" => "Pacific/Samoa",
"-10" => "Pacific/Honolulu",
"-9" => "America/Juneau",
"-8" => "America/Los_Angeles",
"-7" => "America/Denver",
"-6" => "America/Mexico_City",
"-5" => "America/New_York",
"-4" => "America/Caracas",
"-3.5" => "America/St_Johns",
"-3" => "America/Argentina/Buenos_Aires",
"-2" => "Atlantic/Azores",
"-1" => "Atlantic/Azores",
"0" => "Europe/London",
"1" => "Europe/Paris",
"2" => "Europe/Helsinki",
"3" => "Europe/Moscow",
"3.5" => "Asia/Tehran",
"4" => "Asia/Baku",
"4.5" => "Asia/Kabul",
"5" => "Asia/Karachi",
"5.5" => "Asia/Calcutta",
"6" => "Asia/Colombo",
"7" => "Asia/Bangkok",
"8" => "Asia/Singapore",
"9" => "Asia/Tokyo",
"9.5" => "Australia/Darwin",
"10" => "Pacific/Guam",
"11" => "Asia/Magadan",
"12" => "Asia/Kamchatka"
);
return $timezones[$offset];
}
?>
…并使用它进行转换:
date_default_timezone_set(offsetToTimezone($hours));
顺便说一下,我建议你看看这个答案,它为你提供了一种更优雅的方式来实现offsetToTimezone
的工作。
现在您的脚本已经配置在正确的时区,只需请求时间戳:
$timestamp = mktime(0, 0, 0);
如果在某些时候,你需要重置时区为默认,你可能需要date_default_timezone_get
保存它:
$timezone = date_default_timezone_get();
// Change to another timezone based on your offset.
// Get your timestamp.
date_default_timezone_set($timezone);
我必须仔细考虑一下,但我认为这是我一直在寻找的解决方案。如果你认为这个算法不正确,请告诉我。
function getLastMidnightForOffset( $minuteOffset ) {
$today = mktime( 0, 0, 0 );
$tomorrow = $today + 86400;
$yesterday = $today - 86400;
$offset = $minuteOffset * 60;
if ( time() + $offset >= $tomorrow ) {
$localMidnight = $tomorrow - $offset;
} elseif ( time() + $offset >= $today ) {
$localMidnight = $today - $offset;
} else {
$localMidnight = $yesterday - $offset;
}
return $localMidnight;
}