简体   繁体   English

Moment.js,Moment-timezone:在东部时区输入和显示?

[英]Moment.js, Moment-timezone: input and display in eastern timezone?

I've got a javascript app that the user insists that regardless of location of the app user, they want date/times entered by the user in Eastern time.我有一个 javascript 应用程序,用户坚持认为无论应用程序用户的位置如何,他们都希望用户输入东部时间的日期/时间。 That they will be sent to the database and stored, and later displayed again in the app and displayed in Eastern timezone.它们将被发送到数据库并存储,稍后再次显示在应用程序中并以东部时区显示。 So I was looking to use moment.js and moment-timezone, but can't figure out how to make it work.所以我想使用moment.js和moment-timezone,但不知道如何让它工作。 When I try const objMoment = moment(), objMoment appears to contain a time offset from the current time.当我尝试 const objMoment = moment() 时,objMoment 似乎包含与当前时间的时间偏移。 I was wanting to get a moment object that is whatever time, and then objMoment.tz("America/New_York") but I ended up with a time that is 5 hours off from what it should be.我想得到一个时刻对象,无论何时,然后 objMoment.tz("America/New_York") 但我最终得到的时间与它应该的时间相差 5 小时。

        const objMoment = moment();
        const objEastern = objMoment.clone().tz("America/New_York");
        debugger;
          formData.SwoDate = objMoment.toDate();
        debugger;

A few things:一些东西:

  • You don't need to create a local moment and clone it.您不需要创建本地时刻并克隆它。 You can instead construct a moment directly in a specific time zone with:您可以改为直接在特定时区构建时刻:

     moment.tz('America/New_York')
  • Since you call toDate() , the result is always going to be a Date object that represents "now".由于您调用toDate() ,结果将始终是表示“现在”的Date对象。 It doesn't matter if that comes from a Moment that's been set to a different time zone or not.这是否来自设置为不同时区的时刻并不重要。 It's the same moment in time.这是同一时刻

     moment().valueOf() // 1600198416842 moment.utc().valueOf() // 1600198416842 moment.tz('America/New_York').valueOf() // 1600198416842 new Date().valueOf() // 1600198416842 Date.now() // 1600198416842
  • If you want to see the time in a different time zone, you would need to use a function like format instead.如果您想查看不同时区的时间,则需要使用类似format的函数。

     moment.utc().format() // "2020-09-15T19:33:36Z" moment.tz('America/New_York').format() // "2020-09-15T15:33:36-04:00"
  • Moment is a legacy library. Moment 是一个遗留库。 You should probably choose a different library, or perhaps no library at all.您可能应该选择不同的库,或者根本不选择库。 Please read: Moment Project Status请阅读:时刻项目状态

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM