0

I'm calculating the time in minutes using timestamp and moment. So far I can format timestamp with moment but the calculation is a NaN.

This is my code:

function (val) {
   var a = moment.unix(val[0]).format("YYYY-MM-DD hh:mm:ss") // timestamp: 1672531200 
   var b = moment.unix(val[1]).format("YYYY-MM-DD hh:mm:ss") // timestamp: 1672551000 
   var diff = Math.round((b - a) / 60000)
   console.log('A', a) // res: 2023-01-01 12:00:00
   console.log('B', b) // res: 2023-01-01 05:30:00
   console.log('difference', diff) // res: NaN
   return diff + (diff > 1 ? ' minutes' : ' minute')
}

Could you please explain me what I'm doing wrong here?

Rolanda
  • 328
  • 1
  • 9
  • Does this answer your question? [Hour difference between two times(HH:MM:SS a)in momentjs](https://stackoverflow.com/questions/29745873/hour-difference-between-two-timeshhmmss-ain-momentjs) – Arvind Kumar Avinash Jan 27 '23 at 14:53
  • I saw it earlier but I got "diff is not a function" error – Rolanda Jan 27 '23 at 14:56
  • I need to use timestamp because is a value coming from JSON as an string and include it in Apex Chart object values – Rolanda Jan 27 '23 at 14:59

1 Answers1

1

With the .format("YYYY-MM-DD hh:mm:ss") at the end of the first two lines, you are trying to substract two strings.

Just remove the format() calls and it should work :

function calcul(val) {
   var a = moment.unix(val[0]) // timestamp: 1672531200 
   var b = moment.unix(val[1]) // timestamp: 1672551000 
   var diff = Math.round((b - a) / 60000)
   return diff + (diff > 1 ? ' minutes' : ' minute')
}

Regards

Alex
  • 208
  • 1
  • 6