【问题标题】:Get the next Monday in a user's timezone获取用户时区的下周一
【发布时间】:2022-01-15 00:02:15
【问题描述】:

这篇文章非常有用Getting the date of next Monday,它可以帮助您确定如何在 UTC 时间获得下周一。我有以下问题。

我想在用户 A 的时区获取下周一,然后将其转换为用户 B 的时区。我该怎么做?

因此,如果用户 A 的时区是 America/New_York,并且日期是 2022 年 1 月 2 日,我希望得到该时区的下周一。然后将该日期转换为用户 B 的时区。我如何使用 javascript 或 moment js 来做到这一点?

目标是让用户下次有空,以便不同时区的其他用户可以与他预约。

【问题讨论】:

  • 不确定我是否遵循...您如何将日期从客户 A 发送到 B?
  • 您知道下周一的日期,并且您知道所涉及的两个时区,因此创建一个新的 Date 对象该时区作为构造函数字符串的一部分,然后取从那里开始?

标签: javascript momentjs moment-timezone


【解决方案1】:

如果我的问题是正确的,您希望获取不同时区的日期,然后获取下周一,然后将其转换为您想要的时区。如果是这样,这应该可行:

注意:这使用 Moment js 和 moment 时区库。 “带有数据的时刻时区”库有点庞大,所以如果您担心性能,那么 CDN 可能不是尝试 node js 的方式。

function getNextMonday() {
  const now = new Date()
  const today = new Date(now)
  today.setMilliseconds(0)
  today.setSeconds(0)
  today.setMinutes(0)
  today.setHours(0)

  const nextMonday = new Date(today)

  do {
    nextMonday.setDate(nextMonday.getDate() + 1) // Adding 1 day
  } while (nextMonday.getDay() !== 1)

  return nextMonday
}

var cur_date = moment(getNextMonday());
//this gives the corrsponding date on specific time zone of next monday
console.log(cur_date.tz('America/Los_Angeles').format())
<script src="https://momentjs.com/downloads/moment.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.js"></script>

【讨论】:

  • 这里的问题是 cur_Date 不在用户 A 的时区中。它是UTC。如果用户 A 在 America/New_York 而用户 B 在中国,它应该得到用户 A 的时区而不是 UTC 的下周一。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多