简体   繁体   English

使用 moment 将用户定义的时间转换为 UTC

[英]Convert user define time to UTC using moment

We have application where we ask user to define time when they want to publish some content.我们有一个应用程序,我们要求用户定义他们想要发布某些内容的时间。 In our application, user will select that content should publish X(0-5) day before target date and y time (0-23).在我们的应用程序中,用户将 select 内容应在目标日期和 y 时间 (0-23) 之前 X(0-5) 天发布。

So if user create a content with publish date = "09/21/2021" and publish time as 3 it means this content needs to publish at 3 AM on 09/21/2021.因此,如果用户创建发布日期为“09/21/2021”的内容并将发布时间设置为 3,则意味着该内容需要在 09/21/2021 凌晨 3 点发布。

In our Mongo DB we need to store the calculated date as "2021-09-21T07:00:00" So it can be pulled by our Cron Job.在我们的 Mongo DB 中,我们需要将计算出的日期存储为“2021-09-21T07:00:00”,以便我们的 Cron Job 可以提取它。

We tried will following without any success我们尝试将跟随但没有成功

 var promotedDate = "2021-08-19 04:00:00" var fmt = "YYYY-MM-DD hh:mm:ss"; var m = moment.utc(promotedDate, fmt); console.log('promoted date ', tempDate) console.log(m.local().format(fmt)); console.log(m.utc().format(fmt));

But it gives 2021-08-19 12:00:00但它给出了 2021-08-19 12:00:00

Any help?有什么帮助吗?

You can use moment.toISOString() .您可以使用moment.toISOString() That will give you UTC regardless of the timezone of the moment in question thus: 2013-02-04T22:44:30.652Z .因此,无论所讨论moment的时区如何,这都会为您提供 UTC: 2013-02-04T22:44:30.652Z

Since that comes with milliseconds and a Z for Zulu time, we need to strip off the last 5 characters with string.slice() :由于它带有毫秒和Z代表祖鲁时间,我们需要使用string.slice()去除最后 5 个字符:

const promotedDate = "2021-08-19 04:00:00";
const m            = moment.utc(promotedDate, "YYYY-MM-DD hh:mm:ss");
const iso8601      = m.toISOString()
                      .slice(0,-5); // removes milliseconds and `Z` for Zulu

console.log( `promoted: ${promotedDate}` );
console.log( `iso8601:  ${iso8601} );

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

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