-1

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

2 回答 2

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');
于 2019-03-17T14:51:21.933 回答
0

您可以从所有可用时区中选择一个随机时区:

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>

于 2019-03-17T14:51:37.637 回答