Home > Net >  Perform Subtraction in Moment Js
Perform Subtraction in Moment Js

Time:06-23

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.

CodePudding user response:

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()); // Full date string 
console.log(newvalue.year()); // 1977
<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

CodePudding user response:

This is how I would do it using moment.duration() and diff().

You can get the duration in days using asDays() or in hours using asHours().

Please check snippet below :

let start = 1977
let end = 1985
let duration = moment.duration(moment(end.toString()).diff(moment(start.toString())));
console.log(duration.asDays())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>

CodePudding user response:

duration should already represent a duration in seconds, so you can just subtract that from moment(end.toString()).unix() (which represents the number of seconds since the Unix epoch):

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

Keep in mind that in your code you are subtracting the end value from the start value, which is negative since start < end. I don't think this was intended, so you could either use Math.abs() or subtract end from start.

CodePudding user response:

  1. You need to subtract the small value from the large one. Here in your case, you should subtract start from the end
  2. You get the duration value in unix, so you don't need to do it again

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

  • Related