Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Perform Subtraction in Moment Js

I want to subtract the duration value from the end value. How can I do that with moment.js? I am currently getting the error not valid ISO-8601 date format.

let start = 1977
let end = 1985
let duration = moment(start.toString()).unix() - moment(end.toString()).unix();
let newvalue = = moment(end.toString()).unix() - moment(duration.toString()).unix();

The calculation I have for duration works, so I thought to replicate it for newvalue, but that doesn’t work. Am I missing anything? It must be in ISO-8601 format.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use .add or .subtract methods to add/subtract a duration.

Not your question, but I would expect the duration to be end-start, not start-end.

Here is how it could work:

let start = 1977
let end = 1985
let duration = moment(end.toString()).unix() - moment(start.toString()).unix();
let newvalue = moment(end.toString()).subtract(duration, "second");

console.log(newvalue.toString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>

Take note of the message from the authors of momentjs:

we would like to discourage Moment from being used in new projects going forward

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading