简体   繁体   中英

Formatting momentjs date-time

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:

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

You can use this:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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