Home > Back-end >  Subtract two shamsi dates in type script
Subtract two shamsi dates in type script

Time:01-09

I want to subtract two dates I get one from the api One too:

var eventStartTime = new Date (). toLocaleDateString ('fa-IR'). replace (/ ([0-9]) / g, token => String.fromCharCode (token.charCodeAt (0) - 1728));

Today's date

Now I want to reduce them and get the age

Here it becomes a string because of tolocalDateString

And I also use .valueof() again as a string and I can not subtract them

my code:

  let arr;

    this.formsService.get_date_duration().subscribe(res => {
      arr = res

      var eventStartTime = new Date().toLocaleDateString('fa-IR').replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728));


      eventStartTime = eventStartTime.valueOf();

      var eventEndTime = new Date(arr).valueOf();

      var duration = eventStartTime - eventEndTime;


      console.log("duration", duration)
    }
    )

CodePudding user response:

You can use moment or jalali-moment with this function:

const a = '2022-01-09';
const b = '2022-01-08';
moment(a, 'YYYY/MM/DD').diff(moment(b, 'YYYY/MM/DD'), 'days');

If You are using jalali-moment and your input date is in jalali format you have to use it like:

const a = '1400-10-19';
const b = '1400-10-18';
moment(a, 'jYYYY/jMM/jDD').diff(moment(b, 'jYYYY/jMM/jDD'), 'days');

It will return difference in days for other types of results like minutes, hours,... see docs.

You can also use functions like isBefore or isAfter.

moment('2010-10-20').isBefore('2010-12-31', 'year'); // false
moment('2010-10-20').isBefore('2011-01-01', 'year'); // true

In jalali:

moment('1400-10-19', 'jYYYY-jMM-jDD').isBefore('1400-10-18', 'jYYYY-jMM-jDD'); // false
moment('1400-10-19', 'jYYYY-jMM-jDD').isBefore('1400-10-20', 'jYYYY-jMM-jDD'); // true
  •  Tags:  
  • Related