How to get server timezone in javascript

南笙酒味 提交于 2019-12-31 02:44:09

问题


I want to set different timezone in Javascript.Currently It is showing date and time zone of local machine or client's PC date /timezone.

Regards,


回答1:


Javascript is a client-side language and does not interact with the server that way. You'll need to fetch that data from your server-side platform.

Here is some PHP code to get the data you are looking for. You'll either need to put this in your page and echo the result into a JS variable....

<?php
    $date = new DateTime(null, new DateTimeZone('Europe/London'));
    $tz = $date->getTimezone();
    $tzone = $tz->getName();
?>

<script type="text/javascript">
    var timeZone='<?php echo $tzone ?>';
</script>

....or keep the PHP page separate, and fetch the data using AJAX


getTimeZone.php

<?php
    $date = new DateTime(null, new DateTimeZone('Europe/London'));
    $tz = $date->getTimezone();
    echo $tz->getName();
?>

JS

var timeZone=null;
$.get('getTimeZone.php', function(result){
    timeZone=result;
}, 'html');
//I know this is jQuery, not JS, but you get the idea.



回答2:


There is no in-built functionality in JavaScript to do this.

You could embed the time-zone in (e.g.) a hidden field on the page when it is rendered from the server, or implement some sort of http request to actively retrive it from the server.




回答3:


The only way to do this would be to include the timezone in the server's response or to make an ajax call from the javascript browser client to the server to get the server's timezone.



来源:https://stackoverflow.com/questions/5742505/how-to-get-server-timezone-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!