简体   繁体   中英

Calculate the difference between two dates of format (YYYY-MM-DD HH:MM) and display results in minutes

Using moment js, I'm trying this. I couldn't able to resolve this.

const dateOne = "2021-03-08 16:45"
const dateTwo = "2021-03-08 17:45"
console.log(moment.duration(dateTwo.diff(dateOne)));

Consider changing the dates to moment objects by wrapping the strings like this

const dateOne = moment("2021-03-08 16:45")
const dateTwo = moment("2021-03-08 17:45");

const duration = moment.duration(dateTwo.diff(dateOne));
console.log(duration.asHours());

Well there are a couple of issues that you're having:

  • There is no 'diff' property in JS strings (I think you're trying to use moment dates)
  • Moment is no longer being developed because of similar issues you're having

My recommendation would be to migrate to Luxon (the recommended Moment.js alternatives by the Moment.js team). They provide a.diff function for their DateTime objects - https://moment.github.io/luxon/docs/class/src/datetime.js~DateTime.html

What you'll need to do is create a DateTime object for dateOne and dateTwo and then use this function to get the difference (from which you can get the minutes)

Edit :

Just so you know, Moment.js does recommend moving away from it if you can or are building a new project

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