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 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置