How to get server timezone in javascript

前端 未结 3 2014
攒了一身酷
攒了一身酷 2021-01-21 10:59

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,

相关标签:
3条回答
  • 2021-01-21 11:17

    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.

    0 讨论(0)
  • 2021-01-21 11:19

    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.

    0 讨论(0)
  • 2021-01-21 11:21

    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.
    
    0 讨论(0)
提交回复
热议问题