Formatting momentjs date-time

这一生的挚爱 提交于 2021-01-29 16:57:19

问题


Hi everyone I have looked at a few SO questions but have yet to find a solid answer to my problem. Question I have already looked at include:

  • Moment.js returning wrong date
  • Moment JS - parse UTC and convert to Local and vice versa

My question is the following:

I have a basic time selector with times ranging from 4:00am - 8:00pm. I want to use the time selected along with a hard-coded date to format something that looks like this:

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

Here's what I have so far:

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

Where filterText is the string passed in by the select: "4:00AM"

How can i construct something that looks like: "2015-05-09T04:00:00" ?

As of now I am getting the following, which is way off: "2015-02-27T08:20:00+00:00"

When I remove the timezone I get something that is closer, but the time is not changing:

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

回答1:


You can use this:

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



回答2:


You should 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"));

From the moment.js docs

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.

If you don't pass a format string, you may get the correct results, or maybe not. You will see the following message in the console log:

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.

Also, you probably don't need to pass the time zone for this purpose. However, if you id need it to be time zone specific, that would be the wrong way to do it. The moment function doesn't take a time zone parameter. You would need to use the moment-timezone addon, and pass it to the tz function, like this:

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


来源:https://stackoverflow.com/questions/29336358/formatting-momentjs-date-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!