JS-时区选择-获取当前时区

╰+攻爆jí腚メ 2022-04-01 07:11 451阅读 0赞

一个时区选择插件的使用,以及获取当前时区的例子。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
  7. <script src="timezones.full.js"></script>
  8. <script src="moment-timezone-with-data-2012-2022.min.js"></script>
  9. <style>
  10. div {
  11. width: 500px;
  12. margin: 0 auto;
  13. margin-top: 400px;
  14. }
  15. </style>
  16. </head>
  17. <body>
  18. <div>
  19. <select></select>
  20. <br /><br />
  21. <button>获取值</button>
  22. <br /><br />
  23. <span></span>
  24. </div>
  25. </body>
  26. <script>
  27. //初始化
  28. $('select').timezones();
  29. // $('select').val('Asia/Shanghai');
  30. //选中当前时区,有些浏览器不支持
  31. $('select').val(Intl.DateTimeFormat().resolvedOptions().timeZone);
  32. //使用moment-timezone获取当前时区
  33. // $('select').val(moment.tz.guess());
  34. $("button").click(function() {
  35. $("span").html($("select").val());
  36. });
  37. // console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
  38. //推测当前时区
  39. console.log(moment.tz.guess());
  40. //方法可返回格林威治时间和本地时间之间的时差,以分钟为单位。
  41. var d = new Date();
  42. var n = d.getTimezoneOffset();
  43. </script>
  44. </html>

效果:
在这里插入图片描述
Intl是Internationalization API,但是有些浏览器不支持。

  1. Intl.DateTimeFormat().resolvedOptions().timeZone

Intl浏览器支持情况:
在这里插入图片描述
参考

https://caniuse.com/#search=DateTimeFormat
https://github.com/firstandthird/timezones
http://momentjs.com/timezone/

发表评论

表情:
评论列表 (有 0 条评论,451人围观)

还没有评论,来说两句吧...

相关阅读