简体   繁体   中英

Moment JS Setting date format

I have a datetime string from which I am creating a start_time and end_time variable.

Expected Output: start_time should be exactly 2 days from now with the time taken from datetime string and end_time is exactly 3 hours from start_time .

Code

 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script> const time = "2019-12-13T05:30:00+08:00" const date = moment(time); const h = date.hour(); const m = date.minutes(); const s = date.seconds(); const from = moment().add(2, 'days'); var start_time = from.clone().hour(h).minute(m).second(s); var end_time = start_time.clone().add(3, 'hours'); // start_time = start_time.toISOString(); // end_time = end_time.toISOString(); console.log(start_time); // Expected: "2019-12-15T05:30:00+08:00" console.log(end_time); // Expected: "2019-12-15T08:30:00+08:00" </script>

Expected Result:

start_time: "2019-12-15T05:30:00+08:00"

end_time: "2019-12-15T08:30:00+08:00"

Current Result:

start_time: "2019-12-14T21:30:00.604Z"

end_time: "2019-12-15T00:30:00.604Z"

Any idea on how to properly format the date in this case to achieve the expected result?

This is because you are using different time zone. The input is +8 timezone and the output is UTC

If you added .format() , you will see that you actually have the correct value.

 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script> const time = "2019-12-13T05:30:00+08:00" const date = moment(time); const h = date.hour(); const m = date.minutes(); const s = date.seconds(); const from = moment().add(2, 'days'); var start_time = from.clone().hour(h).minute(m).second(s); var end_time = start_time.clone().add(3, 'hours'); // start_time = start_time.toISOString(); // end_time = end_time.toISOString(); // added .format() console.log(start_time.format()); // Expected: "2019-12-15T05:30:00+08:00" console.log(end_time.format()); // Expected: "2019-12-15T08:30:00+08:00" </script>

try like this:

var start_time:moment().add(2,'days');
var end_time:moment().add(2,'days').add(3,'hours')

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