5

In my application I am accessing a remote URL and getting a JSON response like below. The JSON response has a property called created_at.

In JavaScript I need to get the current date minus(-) the created_at date and calculate how many days ago the comment was created.

How can I do that?

{  
   "id":12578834,
   "title":"Joint R&D Has Its Ups and Downs",
   "url":"http://semiengineering.com/joint-rd-has-its-ups-and-downs/",
   "num_points":1,
   "num_comments":0,
   "author":"Lind5",
   "created_at":"9/26/2016 2:28"
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
yasarui
  • 6,209
  • 8
  • 41
  • 75

1 Answers1

15

You can create days and then get difference by subtracting today.getTime() - date.getTime()/NumOfMSecInDay.

Also, time part can cause some issues, so its better to strip it.

var d = {
  "id": 12578834,
  "title": "Joint R&D Has Its Ups and Downs",
  "url": "http://semiengineering.com/joint-rd-has-its-ups-and-downs/",
  "num_points": 1,
  "num_comments": 0,
  "author": "Lind5",
  "created_at": "9/26/2016 2:28"
}

var today = new Date();
var createdOn = new Date(d.created_at);
var msInDay = 24 * 60 * 60 * 1000;

createdOn.setHours(0,0,0,0);
today.setHours(0,0,0,0)

var diff = (+today - +createdOn)/msInDay
console.log(diff)

Edit:

As per @picacode, date.getTime is faster than +date. Following is a JSPer Link

Rajesh
  • 24,354
  • 5
  • 48
  • 79
  • I think you don't need setHours call – maheshiv Nov 24 '16 at 14:52
  • @mplugjan, thanks and apologies for incorrect name – Rajesh Nov 24 '16 at 14:53
  • 1
    @maheshiv if your createdon was say `9/26/22016 20:30` and you check it at `11/24/2016 5:30` will yield `58` and `11/24/2016 21:30` will yield `59`. Hence `setHours` is required – Rajesh Nov 24 '16 at 14:55
  • @maheshiv - always a good idea to normalise the time. If today is DST and daysago is not, then you may get issues – mplungjan Nov 24 '16 at 14:55
  • I thought we can concatenate ':00' at the end and pass to Date function. But I agree with @mplungjan. – maheshiv Nov 24 '16 at 15:01
  • Why there are plus signs before the dates? – mcnk Jun 17 '20 at 06:56
  • @picacode Thats is a shorthand for `date.getTime()` – Rajesh Jun 17 '20 at 07:06
  • Thanks @Rajesh, I was looking into it and found out it was just turning it into a number and performance-wise it is slower than just doing `date.getTime()` I have editted the answer. For the performance test, you can check this link https://jsperf.com/new-date-timing – mcnk Jun 17 '20 at 07:14
  • @picacode Your JSPerf is not up to mark. I'll make a similar one which only compares `getTime` vs `+date`. Also, difference is so small, it can be ignored – Rajesh Jun 17 '20 at 07:53
  • @Rajesh you are right it is just 10 percent faster but anyways it is faster and more readable in my opinion. Thanks for the code. – mcnk Jun 17 '20 at 07:57