问题
Hello friends this my my php code.
<?php
$date3=date_default_timezone_set('Europe/Paris');
echo $abc3=date('Y-m-d h:i:s');
$t3= strtotime($abc3) * 1000;
?>
print date is 2014-01-23 08:43:45
Friends This is my Javascript Code
<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>
The Javascript code is print date is the wrong.
javascript output is under.
13:13:45
please help where i doing mistake.
thank you.
回答1:
You just need to convert client time to server time zone. Use Date.prototype.getUTCHours and etc methods. Also you can use Date.prototype.getTimezoneOffset() to check the time zone difference and notify use if day changed, for example:
<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>
回答2:
Pass the date string directly inside the date function
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>
回答3:
use below:-
<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>
EDIT:-
<?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>
来源:https://stackoverflow.com/questions/21302224/php-timestamp-convert-to-javascript