【问题标题】:Moment Timezone not returning expected result时刻时区未返回预期结果
【发布时间】:2020-10-13 11:34:48
【问题描述】:

我可能在这里做一些愚蠢的事情。但本质上,现在里斯本的时间是下午 12:27

但以下返回 14:27(欧盟中部时间)

  const time = moment.tz("Europe/Lisbon")
  const timeZone = "Europe/Lisbon"
  const format = "'HH[:]mm'"
  const startMoment = moment.tz(item.startTime, format, timeZone); 
  const endMoment = moment(item.endTime, format, timeZone); 
  return time.isBetween(startMoment, endMoment); 

我尝试了几种组合,但每次都得到错误的答案。例如,如果我将 timeZone 设置为“Europe/Warsaw”,它会返回 15:27 而应该是 13:27。

编辑:const currentTime = moment().tz("Europe/London").format() 返回伦敦的正确时间。但是,返回语句moment(currentTime).isBetween(startMoment, endMoment) 仍将“moment(correntTime)”读取为本地时间。

【问题讨论】:

  • 那么,item.startTime 和 item.endTime 是常规的Date 对象吗?无论如何,该代码如何返回时间......它不应该返回一个布尔值.......isBetween 听起来它返回 true 或 false
  • item.startTime 和 item.endTime 是否在给定的时区右侧(例如欧洲/里斯本)?
  • const endMoment = moment(item.endTime, format, timeZone); .... 那里缺少.tz
  • @JaromadaX 没有。对不起,“item.endtime”已经是格式化的时间,不需要转换。它只是返回不能正常工作并且 time.isBetween = 错误时间。

标签: javascript reactjs momentjs moment-timezone


【解决方案1】:

isBetween 返回布尔值。 isBetween 在日期对象上运行。您正在尝试在 time zone 对象上运行。这与日期对象不同

    const time = moment.tz("Europe/Lisbon")
    const timeZone = "Europe/Lisbon"
    const format = "'HH[:]mm'"
    const startMoment = moment().subtract(8, 'months').tz(timeZone).format(); 
    const endMoment = moment(new Date()).tz(timeZone).format() ; 
    console.log("startMoment",startMoment)
    console.log("endMoment",endMoment)
    console.log(moment.tz(new Date(),"Europe/Lisbon").format())
    console.log(moment('2020-09-30').isBetween(startMoment, endMoment));
    <script src="https://momentjs.com/downloads/moment.min.js"></script>
    <script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>

【讨论】:

  • 谢谢,但“item.startTime”与问题无关。这是一个格式化的时间字符串,它可以正常工作。我的格式错误,我可以通过控制台记录 console.log(moment.tz(new Date(),"Europe/Lisbon").format(format)) 得到正确的结果,但我不确定如何在 inBetween 中使用它功能
  • 我已经更新了我的答案,你可以再检查一次。这能解决你的问题吗?
  • const currentTime = moment.tz(new Date(),"Europe/Lisbon,").format() 并返回 ``` return moment(currentTime).isBetween(startMoment, endMoment)`` moment(currentTime) 仍然没有给出预期的结果,因为 currentTime 仍然是错误的。它显示的是 13:08 而不是 14:08。
  • 这是因为您添加了额外的逗号,,这使得.tz 无效。试试这个:const currentTime = moment.tz(new Date(),"Europe/Lisbon").format() 注意Lisbon之后没有逗号
  • 谢谢!但我发现了这一点,请查看上面的编辑。在我尝试将 isBetween 与 currentTime 一起使用之前,它工作正常。 return moment(currentTime).isBetween(startMoment, endMoment) === 只是 localTime 而不是西方 currentTime.isBetween(startMoment, endMoment) === 错误
猜你喜欢
  • 2011-08-09
  • 2010-09-22
  • 2021-05-17
  • 2018-02-19
  • 2018-03-23
  • 2020-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多