1

我正在开发一个需要与时间和时区相关的特定功能的应用程序。这是下面的伪代码,可以简要说明我的疑问

$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";

我想要的是根据事件当前正在发生、将要发生还是已经发生,将事件的状态显示为“Live”、“Upcoming”和“Finished”。

我怎样才能找到独立于国家时区的这种状态?

任何我可以拥有通用功能的方式

$universal_time = get_time_in_utc_for($system_time, $timezone); // similarly for start_time & end_time
4

2 回答 2

1

您有一个良好的开端 -使用 UTC

传统上strtotime()是工作的方法。但是,如果您使用 PHP > 5.3,您可能会发现DateTime类更加灵活。

快速代码示例:

$timestamp = strtotime('2013-03-28 10:00 AM +5:30');
// 1364445000
于 2013-03-28T20:59:36.913 回答
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);
于 2013-03-28T21:52:44.620 回答