0

i'm getting 2 strings from php and i'm trying to get the difference between then using javascript. this is my code:

this.now = Thu Feb 14 2017 16:38:42 GMT-0200 (BRST) this.expiration = Wed Feb 15 2017 15:29:45 GMT-0200 (BRST)

and i want the days difference between this two dates, to show something like "1" day left.

Ivan Moreira
  • 201
  • 2
  • 7

1 Answers1

1

There are several ways to do it:

1) It's possible to use library like [date-fns#differenceInDays]

2) Write your simple diff function

const msInDay = 24 * 3600 * 1000

function diffInDays(startDateString, endDateString) {
  const start = new Date(startDateString)
  const end = new Date(endDateString)

  const ms = end - start
  const fullDays = Math.round(ms / msInDay)

  return fullDays
}
uladzimir
  • 5,639
  • 6
  • 31
  • 50
  • It works perfectly, thank you – Ivan Moreira Feb 15 '17 at 18:25
  • Parsing strings with the Date constructor is not recommended as it's almost entirely implementation dependent. There are [*many good answers*](http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript) to this question already. – RobG Feb 15 '17 at 23:07
  • @Rob well, a lot of answers contains even moment, not only Date constructor. Could you please point to *good answer*? Should I update answer with Date.parse? – uladzimir Feb 16 '17 at 00:02
  • The first answer is fine. Avoid any solution that uses the Date constructor (or Date.parse, they are equivalent for parsing) to parse a string. – RobG Feb 16 '17 at 00:59
  • @RobG but the first answer uses `new Date` :) – uladzimir Feb 16 '17 at 06:12
  • Yes, because that's the only way to create a Date instance. But it doesn't use Date to parse a string, it has its own *parseDate* function. – RobG Feb 17 '17 at 01:12