codegeek codegeek - 1 year ago 75
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"

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download