【问题标题】:Jquery date object by timezone [duplicate]时区的Jquery日期对象[重复]
【发布时间】:2016-12-15 15:23:37
【问题描述】:

我正在尝试获取具有特定时区当前时间的日期对象,

    var options = {
        timeZone: 'Asia/Novokuznetsk',
        year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hour12: false
    },
    formatter = new Intl.DateTimeFormat([], options),
    date_string = formatter.format(new Date()),      
    dsplit = date_string.split(","),
    date_arr = dsplit[0].split("/"),
    time_arr = dsplit[1].split(":"),
    now = new Date(date_arr[2], date_arr[0] - 1, date_arr[1], time_arr[0], time_arr[1], time_arr[2]);

并且now 输出特定时区的正确当前时间。主要问题是此示例并非支持所有时区。有没有更好的方法来获取特定时区当前时间的日期对象?

【问题讨论】:

    标签: jquery date time timezone


    【解决方案1】:

    阿多玛斯: 尝试以下代码以在 calcTime 函数上指定任何时区:

    <html>
    <head>
    <script language="JavaScript">
    
    // function to calculate local time
    // in a different city
    // given the city's UTC offset
    function calcTime(city, offset) {
    
        // create Date object for current location
        d = new Date();
    
        // convert to msec
        // add local time zone offset 
        // get UTC time in msec
        utc = d.getTime() + (d.getTimezoneOffset() * 60000);
    
        // create new Date object for different city
        // using supplied offset
        nd = new Date(utc + (3600000*offset));
    
        // return time as a string
        return "The local time in " + city + " is " + nd.toLocaleString();
    
    }
    
    // get Bombay time
    alert(calcTime('Bombay', '+5.5'));
    
    // get Singapore time
    alert(calcTime('Singapore', '+8'));
    
    // get London time
    alert(calcTime('London', '+1'));
    
    </script>
    </head>
    <body>
    
    </body>
    </html>
    

    参考:http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/

    【讨论】:

    • 我想你的建议应该适合,但我不知道偏移量。时区格式亚洲/新库兹涅茨克、欧洲/基辅等
    • 你可以用这个得到实际的偏移量: var offset = new Date().getTimezoneOffset(); console.log(offset);
    • 它会偏离我的时区。如果我不知道基辅的当前时间,如何知道欧洲/基辅时区的偏移量?
    • Adomas,Javascript 它在时区方面不是那么强大。如果您可以使用 PHP 之类的东西,您可以使用特定城市检索任何时区:php.net/manual/en/timezones.php。你可以做的是尝试在 Javascript 中复制它,创建一个包含所有可用时区的数组。
    • 好吧,我必须使用任何客户端技术.. 没有访问服务器端的权限,但我发现:momentjs.com/timezone/docs 可能是正确的使用方法。感谢所有 cmets
    猜你喜欢
    • 2019-06-05
    • 2019-05-24
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2013-04-24
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    相关资源
    最近更新 更多