简体   繁体   English

使用moment.js(时区)时以(“ YYYY-MM-DD HH:mm”)格式返回日期和时间

[英]Return date and time in (“YYYY-MM-DD HH:mm”) format when using moment.js (timezone)

I am using moment-timezone so I can convert from selected timezone to timezone of a client. 我正在使用moment-timezone,因此可以将所选时区转换为客户端的时区。

I wasn't able to implement it in a better way than this: 我无法以比这更好的方式实现它:

convertSelectedTimeZoneToClients() {
    let timeZoneInfo = {
        usersTimeZone: this.$rootScope.mtz.tz.guess(),
        utcOffset: this.formData.timeZone.offset,
        selectedDateTime: this.toJSONLocal(this.formData.sessionDate) + " " + this.formData.sessionTime 
    };

    let utcTime = this.$rootScope.mtz.utc(timeZoneInfo.selectedDateTime).utcOffset(timeZoneInfo.utcOffset).format("YYYY-MM-DD HH:mm");
    let convertedTime = this.$rootScope.mtz.tz(utcTime, timeZoneInfo.usersTimeZone).format("Z");
    return convertedTime;
}

So basically I am using usersTimeZone: this.$rootScope.mtz.tz.guess() , guess() function to find out timezone from the browser. 因此,基本上我正在使用usersTimeZone: this.$rootScope.mtz.tz.guess() ,guess()函数从浏览器中找出时区。 Then I get values from datetime picker and dropdown and convert them to UTC value by using utcOffset. 然后,我从日期时间选择器和下拉列表中获取值,并通过使用utcOffset将其转换为UTC值。 At the end I want to convert that utc value to user timezone value. 最后,我想将该utc值转换为用户时区值。

I get object like this: 我得到这样的对象:

在此处输入图片说明

_d represent correct value after conversion. _d表示转换后的正确值。 I have tried adding bunch of different .format() paterns on convertedTime variable, but I am not able to retrive time in this format: "YYYY-MM-DD HH:mm". 我尝试在convertedTime变量上添加一堆不同的.format()模式,但是无法以以下格式检索时间:“ YYYY-MM-DD HH:mm”。 I guess it works differentlly than when using .utcOffset() function. 我猜它的工作方式与使用.utcOffset()函数时不同。

Can anybody help me with this? 有人可以帮我吗?

You don't need to guess the client time zone to convert to local time. 您无需猜测客户端时区即可转换为本地时间。 Just use the local function. 只需使用local功能。

For example: 例如:

moment.tz('2016-01-01 00:00', 'America/New_York').local().format('YYYY-MM-DD HH:mm')

For users located in the Pacific time zone, this converts from Eastern to Pacific and you get an output string of "2015-12-31 21:00" . 对于位于太平洋时区的用户,这将从东部转换为太平洋,并且您将获得输出字符串"2015-12-31 21:00" For users in other time zones, the output would be different, as expected. 对于其他时区的用户,输出将与预期的不同。

You don't need to format to a string and re-parse it, or manually manipulate the UTC offset either. 您不需要格式化为字符串并重新解析它,也不需要手动操作UTC偏移量。 That is almost never warranted. 那几乎是没有根据的。

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

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