我正在开发一款需要与时间和时间相关的特定功能的应用。时区。 下面是一个伪代码,可以提供有关我的疑问的简要说明
$start_time = "10:00 AM"; // starting time of an event
$end_time = "11:00 AM"; // ending time of an event
$system_time = "1:30 AM";
$timezone = "India +5:30";
我想要的是根据事件当前是否正在发生或将要发生的事件,将事件的状态显示为“实时”,“即将结束”和“完成”。
如何找到独立于国家时区的此状态?
任何方式我可以拥有像
这样的通用功能$universal_time = get_time_in_utc_for($system_time, $timezone); // similarly for start_time & end_time
答案 0 :(得分:1)
你有个好的开始 - 使用UTC 。
传统上strtotime()
是工作的方法。但是,如果您使用的是PHP> 5.3,您可能会发现DateTime类更灵活。
快速代码示例:
$timestamp = strtotime('2013-03-28 10:00 AM +5:30');
// 1364445000
答案 1 :(得分:1)
<?
// Not sure where you're gonna run this
$b = PHP_EOL . "<br/>";
// Create your events in their natual start/end time per that country/TZ
$eventStartMyTime = '2013-03-28 11:30:00';
$eventEndMyTime = '2013-03-28 16:30:00';
$eventTimeZone = new DateTimeZone('Asia/Calcutta');
$startTime = new DateTime($eventStartMyTime, $eventTimeZone);
$endTime = new DateTime($eventEndMyTime, $eventTimeZone);
// Now when the system deals with dates, it's going to
// deal with them all in UTC (DateTime object can do this)
// A Unix timestamp is inherently "in UTC"
// Store these values in a db if you need to
$startTS = $startTime->getTimestamp();
$endTS = $endTime->getTimestamp();
// Function to get status
function getStatus($dateTime, $start, $end) {
// Get UTC timestamp for the input
$time = $dateTime->getTimestamp();
// Check against event times
switch(true) {
case $time >= $start && $time < $end: return "LIVE";
case $time >= $end: return "ENDED";
case $time <= $start: return "UPCOMING";
}
}
// Let's walk through some scenarios
$testUpcoming = new DateTime('2013-03-21 00:00:00', new DateTimeZone('Asia/Calcutta'));
$testLive = new DateTime('2013-03-28 15:30:00', new DateTimeZone('Asia/Calcutta'));
$testEnded = new DateTime('2013-03-28 23:30:00', new DateTimeZone('Asia/Calcutta'));
$testNewYork = new DateTime('2013-03-28 12:30:00', new DateTimeZone('America/New_York'));
$testPyongyang = new DateTime('2013-03-28 12:30:00', new DateTimeZone('Asia/Pyongyang'));
// Use a fixed TZ (the TZ of the server)
// Should be UPCOMING
echo getStatus($testUpcoming, $startTS, $endTS) . $b;
// Should be LIVE
echo getStatus($testLive, $startTS, $endTS) . $b;
// Should be ENDED
echo getStatus($testEnded, $startTS, $endTS) . $b;
// Pretend we're running on a server in New York
// Same timestamp, different TZ
// Should be ENDED
echo getStatus($testNewYork, $startTS, $endTS) . $b;
// Pretend we're running on a server in Pyongyang
// Same timestamp, different TZ
// Should be UPCOMING
echo getStatus($testPyongyang, $startTS, $endTS) . $b;
$now = new DateTime();
echo "Our current timezone is: " . $now->getTimezone()->getName() . $b;
echo "And the event is: " . getStatus($now, $startTime, $endTime);