dongshi7433 2013-04-12 10:33
浏览 38
已采纳

PHP日期时间格式和字符串

I'm building a Joomla component for online exams and I'm struggling with format conversions. Basically I want to get a difference between to dates (in seconds) and then convert them to minutes but no matter what I try and what I search online (including SO) I can't seem to get things working properly.

I have the following code:

<?php
$session =& JFactory::getSession();
$sessionStuff = $session->get('quizSession');

$time_config =& JFactory::getConfig();
$time_jnow =& JFactory::getDate();
$time_jnow->setOffset( $time_config->getValue('config.offset' ));
$time_now = strtotime($time_jnow);
$started_time = strtotime($sessionStuff['lineSession']['started_on']);

$elapsedtime = /*gmdate("H:i:s",*/ abs($started_time - $time_now)/*)*/;
echo "Start_time: " . $started_time . '- Type: ' . gettype($started_time). '<br/>';
echo "Now: " . $time_now . '- Type: ' . gettype($time_now). '<br/>';
echo "Elapsed time: " . $elapsedtime . /*'- Type: ' . gettype($elapsedtime) .*/ '<br/>';

$availabletime = $started_time - $elapsedtime;

if(empty($sessionStuff)){
    $availabletime = ($this->quiz->time_limit) ? $this->quiz->time_limit : 0;
} else {
    $availabletime = $started_time - $elapsedtime;
}

echo "Available: " . $availabletime . '- Type: ' . gettype($availabletime);
?>

Which outputs the following:

Start_time: 1365756958- Type: integer

Now: 1365757510- Type: integer

Elapsed time: 552

Available: 1365756406- Type: integer

Then I have this JS code which receives a value (in minutes) and converts it to the correct format:

    var hours ;
    var minutes ; 
    var seconds ;
    var t ;
    var availableTime ;
    var remainingTime ;

window.onload = function () {

    listener();

    availableTime = <?php
                        echo ($this->quiz->time_limit) ? $this->quiz->time_limit : 0;;                       
                    ?> ;
    if (availableTime)
    {
        hours = Math.floor(availableTime / 60) ;
        minutes = availableTime % 60;

        if (hours < 10) {
            hours = '0' + hours ;
        }

        if (minutes < 10) {
            minutes = '0' + minutes ;
        }

        seconds = '00' ;

        var timer = document.getElementById('timer') ;
        timer.innerHTML = '<?php echo JText::_('TIME_REMAINING') ; ?> ' + hours + ":" + minutes + ":" + seconds ;

        remainingTime = availableTime *= 60 ;

        updateTimer();
    }
}

function pad(number, length) 
{
    var str = '' + number;
    if (str.length < length) {
        str = '0' + str;
    }

    return str;
}

function updateTimer()
{
    seconds -= 1 ;
    seconds = pad(seconds, 2) ;

    if (seconds < 0)
    {
        seconds = '59' ;
        minutes -= 1 ;
        minutes = pad(minutes, 2) ;

        if (minutes < 0)
        {
            minutes = '59' ;
            hours -= 1 ;
            hours = pad(hours, 2) ;

            if (hours < 0)
            {
                hours = minutes = seconds = '00' ;
                document.getElementById('timeUp').value = 1 ;
                document.jquarks_quiz.submit();
                return true ;
            }
        }
    }

    var timer = document.getElementById('timer') ;
    timer.innerHTML = '<?php echo JText::_('TIME_REMAINING') ; ?> ' + hours + ':' + minutes + ':' + seconds ;

    remainingTime -= 1 ;
    if (Math.floor(availableTime / 10) == remainingTime ) 
    {
        timer.style.color="white" ;
        timer.style.backgroundColor = "#DD0000" ;
    }

    t = setTimeout("updateTimer()", 1000);
}

If I use the "native" formats (in PHP) for this piece of code:

$time_now = $time_jnow;
$started_time = $sessionStuff['lineSession']['started_on'];

I get the ouput:

Start_time: 2013-04-12 09:55:58- Type: string

Now: 2013-04-12 10:23:20- Type: object

Now, What I intend is to calculate the time difference between 'started_time' and 'time_now' and (if it's a page refresh and the session is set) subtract the 'elapsedtime' to the 'started_time' so that the timeout counter will continue from where it left off.

No matter what I try, I can't seem to get things working correctly. Could anyone point me in the right direction? I've already lost way too much time with this and PHP is not my forte. How can I achieve the intended goal?

EDIT:

I realize that JS 'availableTime' is getting a constant time, but that is just for debugging purposes for now. Once everything is working fine it will be fed with the PHP '$availabletime' output.

EDIT 2:

I seem to not have been explicit in what the objective is. Once an exam starts, let's say there are 15 minutes available. Assuming that after 1min and 31sec (00:01:31) the user refreshes the page, the available time should be 13minutes and 29 seconds (00:13:29). This is the behaviour I'm not being able to achieve although I can perform the calculations for how much time (in seconds) has passed.

  • 写回答

1条回答 默认 最新

  • dougupang0901 2013-04-12 10:47
    关注

    Here is a really simple way to do it.

     // Define your time strings
     $date1 = new DateTime("2013-01-01 07:00:00");
     $date2 = new DateTime("2014-01-01 03:17:00");
    
     // Perform a bit of black hoodoo magic
     $interval = $date1->diff($date2,true);
    
     // Output the result in a formatted fashion
     echo $interval->format("%d days %h hours %i minutes %s seconds");
     // Or as a number of seconds. This is a bit more complicated.
     echo (($interval->y * 365 * 24 * 60 * 60) + 
               ($interval->m * 30 * 24 * 60 * 60) + 
               ($interval->d * 24 * 60 * 60) + 
               ($interval->h * 60 * 60) + 
               ($interval->i * 60) + 
               $interval->s); 
     // For more info, check this out along with the doc:
     var_dump($interval);
    

    This allows you to abstract away all the calculations you are doing in order to focus on the logic. What is going wrong?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100