0

I am building an Instagram feed with JQuery into my site and want to show how long has passed since the post was submitted in a short form like: 23H or 2D or 3M or 1Y depending on how long its been. I've got my two date objects but I can't figure our how to calculate the difference and display it how i want.

I am fairly new to JS/Jquery and as far as i could get was:

var pd = new Date(postDate);
var nd = new Date();
var nd = nd.getTime();
var difference = nd-pd;

How do I calculate the difference between two dates in hours, days, months and years?

Thanks.

Morten Kristensen
  • 7,412
  • 4
  • 32
  • 52

4 Answers4

2

Doing anything with dates is generally painful. If you aren't committed to using that exact format, you can use a library for this instead.

moment.js has a .fromnow() function.

or timeago.js can be used to update the element on the page periodically, so if the user leaves the page open for a few minutes, the time stamps will count up.

CodingWithSpike
  • 42,906
  • 18
  • 101
  • 138
1

You can do this to get the time elapsed since posted

var timeDiff = Math.abs(nd.getTime() - pd.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
Bibhu
  • 4,053
  • 4
  • 33
  • 63
0

you can try like this.

var pd = new Date(postDate);
var nd = new Date();


var Hours = nd.getHours() - pd.getHours();
var Days  = nd.getDay() - pd.getDay();
var Months = nd.getMonth() - pd.getMonth();
var Years  = nd.getYear() - pd.getYear();

or get millisecods diference

var miliseconds = (nd - pd).getTime(); //gets time  in miliseconds since 1/1/1970

then use your logic to calculate hours, days, months and years

you can have a look at this Work with a time span in Javascript moments

ar date1 = new Date("7/Nov/2012 20:30:00"); var date2 = new Date("20/Nov/2012 19:15:00");

var diff = date2.getTime() - date1.getTime();

var days = Math.floor(diff / (1000 * 60 * 60 * 24)); diff -= days * (1000 * 60 * 60 * 24);

var hours = Math.floor(diff / (1000 * 60 * 60)); diff -= hours * (1000 * 60 * 60);

var mins = Math.floor(diff / (1000 * 60)); diff -= mins * (1000 * 60);

var seconds = Math.floor(diff / (1000)); diff -= seconds * (1000);

console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");

Community
  • 1
  • 1
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
0

My solution is dirty but direct: calculate them by myself.

Record start time:

var BEGIN_TIME=new Date();
var HOUR=BEGIN_TIME.getHours();
var MINUTE=BEGIN_TIME.getMinutes();
var SECOND=BEGIN_TIME.getSeconds();

Then do so some math

  var today=new Date();
  h=today.getHours();
  m=today.getMinutes();
  s=today.getSeconds();

  s = s - SECOND;
  if (s<0) { s=s+60; m=m-1; }
  m = m - MINUTE;
  if (m<0) { m=m+60; h=h-1; }
  h = h - HOUR;
Endle_Zhenbo
  • 538
  • 4
  • 23