codegeek codegeek - 9 days ago 6
Javascript Question

How to calculate X days ago in javascript

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"
}

Answer

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)

Comments