格式化 momentjs 日期时间

Formatting momentjs date-time

大家好,我已经查看了一些 SO 问题,但尚未找到解决我的问题的可靠答案。我已经看过的问题包括:

我的问题如下:

我有一个基本时间 select 或者时间范围为 4:00am - 8:00pm。我想使用时间 selected 和硬编码日期来格式化如下所示的内容:

"2015-05-03T04:00:00"

这是我目前的情况:

time = moment("2015/05/09 " + filterText, "America/New_York")
console.log(time.format())

其中filterText是select传入的字符串:"4:00AM"

我如何构建看起来像这样的东西:"2015-05-09T04:00:00"

截至目前,我得到以下信息,这还差得远:"2015-02-27T08:20:00+00:00"

当我删除时区时,我得到了更接近的东西,但时间没有改变:

time = moment("2015/05/09 " + filterText)
console.log(time.format())
"2015-05-09T08:00:00-07:00" <--- remains at 7:00 even if filterText is 8:00 or 9:00

你可以使用这个:

time = moment("2015/05/09 " + filterText);
console.log(time.format("YYYY-MM-DDTHH:mm:ss"));

你应该specify a format string when parsing:

time = moment("2015-05-09 " + filterText, "YYYY-MM-DD hh:mmA");
console.log(time.format("YYYY-MM-DDTHH:mm:ss"));

来自 moment.js 文档

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

如果您不传递格式字符串,您可能得到正确的结果,也可能不会。您将在控制台日志中看到以下消息:

Deprecation warning: moment construction falls back to js Date. This is discouraged and will be removed in upcoming major release. Please refer to https://github.com/moment/moment/issues/1407 for more info.

此外,您可能不需要为此目的传递时区。但是,如果您需要它是特定于时区的,那将是错误的方法。 moment 函数不采用时区参数。您需要使用 moment-timezone 插件,并将其传递给 tz 函数,如下所示:

time = moment.tz("2015-05-09 " + filterText, "YYYY-MM-DD hh:mmA", "America/New_York");
console.log(time.format("YYYY-MM-DDTHH:mm:ss"));