codegeek codegeek - 2 months ago 18
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


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

How can I do that?

"title":"Joint R&D Has Its Ups and Downs",
"created_at":"9/26/2016 2:28"


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": "",
  "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;


var diff = (+today - +createdOn)/msInDay