duanbiaojin8860 2012-07-25 21:03
浏览 61
已采纳

Javascript .getHours()返回奇怪的结果

I'm converting a PHP timestamp into a human readable form in javascript:

<script type="text/javascript">

    var timeleft = new Date( <?php echo $lefttime; ?> * 1000 );

    var hours = timeleft.getHours();
    var minutes = timeleft.getMinutes();
    var seconds = timeleft.getSeconds();

    var countdown = function() {

    console.log( "You have " + hours + ":" + minutes + ":" + seconds + " seconds left" );

</script>

The minutes and seconds work but I'm getting strange results for the hours. For example:

Timestamp: 1976

Function returns: 19:32:56

Any ideas why I'm getting "19" from .getHours() ?

  • 写回答

1条回答 默认 最新

  • duankaolei2921 2012-07-25 21:07
    关注

    I'm going to hazard a guess that you're in Eastern Time. What you are seeing is $lefttime seconds after the epoch, which in the case of EST is 7PM.

    XKCD

    To fix it, just use basic math:

    var timeleft = <?php echo $lefttime; ?>;
    var hours = Math.floor(timeleft/3600);
    var minutes = Math.floor(timeleft/60)%60;
    var seconds = timeleft%60;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?