1

I need to compare two dates in my React Native app: current date with the server one in UTC format. What's the best approach here?

I thought about converting two dates into milliseconds and then converting them.

Example:

2019-06-20T14:26:58Z - milliseconds

current date - milliseconds

So, what is the best approach here?

It's React Native, so it should work without connected chrome debugger.

lecham
  • 2,294
  • 6
  • 22
  • 41
  • Modern ECMAScript implementations will parse 2019-06-20T14:26:58Z natively, however older browsers may not. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jul 26 '19 at 22:40

2 Answers2

0

The momentjs query API has several useful methods for comparing dates. Here's an example of the isSame method. There are others including isSameOrBefore, isAfter, isSameOrAfter to name a few.

// convert current date to UTC
const currentDateUtc = moment(currentDate).utc();

// check if current date is the same as the server date
currentDateUtc.isSame(moment(serverDate).utc())

Read more about moment's query API in their docs.

Onel Harrison
  • 1,244
  • 12
  • 14
0

You can use Date.getTime().

const serverTime = new Date('2019-06-20T14:26:58Z')
const currentTime = new Date()

console.log({
  serverTime: {
    milliseconds: serverTime.getTime(),
    toString: serverTime.toString()
  }
})

console.log({
  currentTime: {
    milliseconds: currentTime.getTime(),
    toString: currentTime.toString()
  }
})

console.log(serverTime.getTime() < currentTime.getTime())
Zaytri
  • 2,582
  • 2
  • 13
  • 19