随机位置数组-moment-timezone.js

时间:2019-03-17 14:29:40

标签: javascript arrays momentjs moment-timezone

如何根据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>

2 个答案:

答案 0 :(得分:0)

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

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');

答案 1 :(得分:0)

您可以从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>

相关问题