【问题标题】:Array of random locations - moment-timezone.js随机位置数组 - moment-timezone.js
【发布时间】:2019-03-17 14:29:39
【问题描述】:

如何根据moment-timezone.js 找到随机位置?我想在您每次刷新页面时显示一个新位置。

当前代码:

<hero>
    <div id="hover">
    <h2>Present time</h2>
    <div id="time"></div>
    </div>
</hero>

<script>

(function clock() {
  var now = moment().format('lll'); //local time

  /*
  I want many of these..
  moment.tz("Europe/Berlin").format('lll');
  */

  var time = document.getElementById('time');
  time.innerHTML = now;

  setInterval(clock, 1000);
})();

</script>

【问题讨论】:

标签: javascript arrays momentjs moment-timezone


【解决方案1】:

您可以从all available timezones 中选择一个随机时区:

const timezones = moment.tz.names();
const randTimezone = timezones[Math.floor(Math.random() * timezones.length)];
const now = moment.tz(randTimezone).format('lll');

document.write(randTimezone, '<br>', now);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>

【讨论】:

  • 谢谢!对不起,你介意把它写在 hastebin/pastebin 里吗?我的 js 太差了……:/
【解决方案2】:

您可以通过从所有时区中选取一个随机元素来获得一个随机时区。

var all = moment.tz.names();
var randomTimeZone = all[Math.floor(Math.random()*all.length)];
// Use it in the code as
moment.tz(randomTimeZone).format('lll');

【讨论】:

    猜你喜欢
    • 2019-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 1970-01-01
    • 2017-02-19
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多