PHP时间戳转换为javascript?

时间:2014-01-23 07:44:47

标签: javascript php timestamp

朋友您好,这是我的PHP代码。

<?php
   $date3=date_default_timezone_set('Europe/Paris');
   echo $abc3=date('Y-m-d h:i:s');
   $t3= strtotime($abc3) * 1000;
?>

打印日期为2014-01-23 08:43:45

朋友这是我的Javascript代码

<script>
 var t3=<?php echo $t3; ?>;
function update_clock3(){

var now = new Date(Number(t3));

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

alert(hours +":"+ minutes + ":" + seconds); 

}
</script>

Javascript代码是打印日期错误。

javascript输出正在。

13时十三分45秒

请在我犯错的地方帮忙。

谢谢。

3 个答案:

答案 0 :(得分:2)

您只需将客户端时间转换为服务器时区即可。使用Date.prototype.getUTCHours等方法。此外,您可以使用Date.prototype.getTimezoneOffset()检查时区差异,并在更改日期时通知使用,例如:

<script>

    var t3=<?php echo $t3; ?>;
    function update_clock3(){

        var now = new Date(Number(t3));
        var year = now.getUTCFullYear();
        var month = now.getUTCMonth();
        var day = now.getUTCDate();
        var hours = now.getUTCHours();
        var minutes = now.getUTCMinutes();
        var seconds = now.getUTCSeconds();  
        //local zone - UTC zone, so +1 UTC will be -60
        var offset = now.getTimezoneOffset()/60;
        //convert hours from UTC time zone to local
        var minutesOffset = offset % 1;
        var localHours = hours - Math.floor(offset);
        var localMinutes = minutes - minutesOffset * 60; 
        var localDate = new Date(year,month, day, localHours, localMinutes, seconds);

        //day can be change by adding offset
        if (localDate.getDate() !== day) {
            alert("You have another day");
        }

        alert("UTC time:" + hours +":"+ minutes + ":" + seconds); 

    }
</script>

答案 1 :(得分:-1)

使用以下: -

<script>
var t3 = '<?php echo $t3; ?>';

function update_clock3(){

    var now = new Date(t3);

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

    alert(hours +":"+ minutes + ":" + seconds); 

}
</script>

修改: -

<?php
   $date3=date_default_timezone_set('Europe/Paris');
   echo $abc3=date('Y-m-d h:i:s');
   $t3= strtotime($abc3) * 1000;
?>

<script>
var t3 = '<?php echo $t3; ?>';
alert(t3);

</script>

答案 2 :(得分:-1)

将日期字符串直接传递到日期函数

http://www.w3schools.com/jsref/jsref_obj_date.asp
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to display the hour of the time right now.</p>

<button onclick=" update_clock3()">Try it</button>

<script>

 var t3='2014-01-23 08:43:45';
function update_clock3(){

var now = new Date(t3);

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

alert(hours +":"+ minutes + ":" + seconds); 

}

</script>

</body>
</html>