1

I'm using the Scala Play framework and I have a form that lets a user search for records, they can then search using today's date and a time stamp 2016-12-17T09:26:47.676Z to create a search range. Note that I mean a 24 hour period, as a single day is usually defined, and not as a difference in a date definition.

I don't have any experience with Javascript, I'd like to compare today's date with this time stamp, calculate the difference in days, and then return the amount of whole days between the two time stamps e.g if the two timestamps had 48 hours difference then it would return 2 days.

I can declare the search time stamp in the script tag on the HTML page, but I would like to know how to call today's date, do some logic to calculate the difference between the dates DaysDifference, and then call this variable in a link on the page:

<a target="_blank" href="@baseLogsUrl/#/discover?_g=(time:(from:no@DaysDifference/d,to:now))&_a=(query:(query_string:(query:'@data._id')))">

ChazMcDingle
  • 635
  • 2
  • 10
  • 18
  • Duplicate of [*How do I get the number of days between two dates in JavaScript?*](http://stackoverflow.com/questions/542938/how-do-i-get-the-number-of-days-between-two-dates-in-javascript)? You should define what a day is: a 24 hour period, or change in date? – RobG Dec 19 '16 at 11:58

1 Answers1

4

You can compute the difference between the current date and a timestamp with the Date API like this: Date.now() - Date.parse('2016-12-17T09:26:47.676Z'). This will return the difference in milliseconds, so we can divide the answer by the number of milliseconds in a day to obtain the difference in days. Summarizing:

var MS_IN_A_DAY = 1000 * 60 * 60 * 24;
var difference = Date.now() - Date.parse('2016-12-17T09:26:47.676Z');
var daysDifference = Math.floor(difference/MS_IN_A_DAY);
jobB
  • 411
  • 3
  • 10
  • 1
    It may be good to create Date objects and zero the hours. Where daylight saving is observed, there are days with more than 24 hours and some less. Also, from 23:50 on one day to 00:15 the following day may be required to be one day (or not). – RobG Dec 19 '16 at 12:00