0

If I have a date in either of the following formats:

  • 03/17/2010 00:09:12 PM
  • 03/17/2010 00:09:12Z

And I want to do datetime math on them, how do I use moment in react to convert and use them properly? For example: If I wanted to compare a date time in the past to right now and take the difference and convert that into a datetime format?

1 Answers1

0

Step 1: To use moment's methods, you need to convert Date object or string to moment object:

Let's say we have:

let firstDate = "03/17/2010 00:09:12 PM"
let secondDate = "03/18/2010 00:09:12Z"

Convert them to moment object:

firstDate = moment(firstDate)
secondDate = moment(secondDate)

Step 2: Check for moment methods and use the one that you need. In this case, I would recommend using isSameOrAfter to compare and diff to get the difference between moment objects:

const isFirstDateBeforeSecondDate = firstDate.isSameOrAfter(secondDate)

const differentBetweenTwoDates = firstDate.diff(secondDate, 'days')

In short:

const isFirstDateBeforeSecondDate = moment(firstDate).isSameOrAfter(moment(secondDate))

const differentBetweenTwoDates = moment(firstDate).diff(moment(secondDate), 'days'))
agentp
  • 335
  • 4
  • 17
  • Just a small note here, moment is a javascript library, which means it is the same in react or vanilla js or any other framework/library of javascript – agentp Mar 18 '21 at 06:27
  • Thank you. I'm searching now on how to convert the final number to an actual time representation. Any help would be appreciated. Right now I'm getting a number back that looks like: 97360000. – Mike Sterling Mar 18 '21 at 15:04
  • I figured it out I just had to do some math on the minutes. https://stackoverflow.com/questions/41391403/how-to-convert-minutes-to-timehhmmss I was hoping there was one method/function that would do this for me but I guess not. No biggie though. – Mike Sterling Mar 18 '21 at 16:01
  • "Right now I'm getting a number back that looks like: 97360000" - This is call Epoch time, search the keyword with moment, you should get the result – agentp Mar 19 '21 at 03:50