1

Hope you are all well,

I've been struggling to find a way to display the amount of time that has passed since a specific date in years, months, weeks and days. The closest i have found, is this below but i can quite work out how to get it to display the years and months.

Any tips would be greatly appreciated.

Thanks

window.onload = function() {
  doTime('jan,01,2017,00:00:01');
}

function doTime(then) {

  now = new Date();
  then = new Date(then);

  difference = (now - then);

  days = Math.floor(difference / (60 * 60 * 1000 * 24) * 1);
  hours = Math.floor((difference % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1);
  mins = Math.floor(((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1);
  secs = Math.floor((((difference % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1);

  document.getElementById('timer').firstChild.nodeValue =

    +days + ' days ' + hours + ' hours ' + mins + ' minutes ' + secs + ' seconds';
  clearTimeout(doTime.to);
  doTime.to = setTimeout(function() {
    doTime(then);
  }, 1000);
}
<div id="timer">&nbsp;</div>

— thanks for the suggestion of the previous post, sadly i have tried that and i can only get it to work the difference between two actual dates, i cant get it to automatically make the end date now so it counts up automatically as time goes on.

— i have done some more fiddling and managed to get to this, being new to js, would you guys say this is pretty close? thanks

var startDateTime = new Date(2012,5,24,09,43,0,0); // YYYY (M-1) D H m s 
(start time and date from DB)
var startStamp = startDateTime.getTime();

var newDate = new Date();
var newStamp = newDate.getTime();

var timer;

function updateClock() {
    newDate = new Date();
    newStamp = newDate.getTime();
    var diff = Math.round((newStamp-startStamp)/1000)

    var years = Math.floor(diff/(12*4.3479*7*24*60*60));
     diff = diff-(years*12*4.3479*7*24*60*60)


    var months = Math.floor(diff/(4.3479*7*24*60*60));
    diff = diff-(months*4.3479*7*24*60*60)

    var weeks = Math.floor(diff/(7*24*60*60));
    diff = diff-(weeks*7*24*60*60)

    var days = Math.floor(diff/(24*60*60));
    diff = diff-(days*24*60*60);
    var hours = Math.floor(diff/(60*60));
    diff = diff-(hours*60*60);
    var mins = Math.floor(diff/(60));
    diff = diff-(mins*60);
    var secs = diff;

    document.getElementById("time-elapsed").innerHTML = years+" years, 
"+months+" months, " +weeks+" weeks, " +days+" days, "+hours+" hours and 
"+mins+" minutes,";
}

setInterval(updateClock, 1000);



<div id="time-elapsed"></div>
lionnn
  • 21
  • 5
  • 3
    Try by using `momentjs` library. It will help to handle date in javascript: https://momentjs.com/ – ADreNaLiNe-DJ Jul 27 '17 at 11:11
  • 1
    What's not working?? – Salketer Jul 27 '17 at 11:12
  • Possible duplicate of [Difference between two dates in years, months, days in JavaScript](https://stackoverflow.com/questions/17732897/difference-between-two-dates-in-years-months-days-in-javascript) – Salketer Jul 27 '17 at 11:16
  • shouldn't you use getTime for calculating the difference? and setInterval may suit better to your needs than setTimeout – Emre Türkiş Jul 27 '17 at 11:24
  • Do you have to be exact? Because some days have 23 hours, and some 25... At least when there's daylight savings. – Salketer Jul 27 '17 at 13:15
  • exact would be lovely but i think as close as possible would be great, so if days had 24 hours always and i was able to work so months with more and some with less that would be great. – lionnn Jul 27 '17 at 13:45

2 Answers2

1

Simple, approximate difference

function calculateDifference(thenString) {
  const second = 1000
  const minute = 60 * second
  const hour = 60 * minute
  const day = 24 * hour
  const month = 30 * day // approximately
  const year = 365 * day // approximately

  const now = new Date();
  const then = new Date(thenString);

  let difference = (now - then);
  const time = [{ year }, { month }, { day }, { hour }, { minute }, { second }].map((item, i, a) => {
    const [[unitName, unit]] = Object.entries(item)
    const units = difference / unit | 0
    difference -= unit * units
    const maybePlural = units === 1 ? "" : "s"
    return units > 0 ? units + " " + unitName + maybePlural : ""
  }).filter(x => x)

  const formattedTime = time.length > 1 ? [...time.slice(0, -1), "and", time.slice(-1)].join(" ") : time[1]
  return formattedTime
}

function displayDifference() {
  displayBox.textContent = calculateDifference(dateInput.value + ", " + timeInput.value)
}

const dateInput = document.querySelector(".date")
const timeInput = document.querySelector(".time")
const displayBox = document.querySelector(".js-display-difference")
dateInput.addEventListener("change", displayDifference)
timeInput.addEventListener("change", displayDifference)
displayDifference()
setInterval(displayDifference, 1000)
<h3>
  since
 <input class="date" type="date" value="2017-01-01"/>
 <input class="time" type="time" value="00:00"/>
 elapsed
 <span class="js-display-difference"></span> 

</h3>

Precise difference with momentjs and precise range plugin

function calculateDifference(thenString) {
 var m1 = moment(Date.now())
 var m2 = moment(new Date(thenString))
 var diff = moment.preciseDiff(m1, m2)
  return diff
}

function displayDifference() {
  displayBox.textContent = calculateDifference(dateInput.value + ", " + timeInput.value)
}

const dateInput = document.querySelector(".date")
const timeInput = document.querySelector(".time")
const displayBox = document.querySelector(".js-display-difference")
dateInput.addEventListener("change", displayDifference)
timeInput.addEventListener("change", displayDifference)
displayDifference()
setInterval(displayDifference, 1000)
<script src="https://unpkg.com/moment@2.18.1"></script>
<script src="https://unpkg.com/moment-precise-range-plugin@1.2.3"></script>
<h3>
  since
 <input class="date" type="date" value="2017-01-01"/>
 <input class="time" type="time" value="00:00"/>
 elapsed
 <span class="js-display-difference"></span> 
marzelin
  • 10,790
  • 2
  • 30
  • 49
0

I'm not an IT expert so there is probably a better way, but what I have done seems to work. An example can be seen here: Date difference in action

My approach was not to workout the difference in days from the first date but to work out the day position in the 'to date' from the day position in the 'from date'. i.e. on my 60th birthday there had been 15 leap years since I was born, but those days aren't counted. I am 60 years old not 60 years and 15 days.

And just to prove I'm not an IT expert I am unable to post the code but you can view the source code in the example. BTW I only use chrome / edge so it's not been tested on other platforms.

  • can you check link, seems it is for wrong resource – zhisme Dec 02 '20 at 08:32
  • i have isolated the code and example to example page, which calculates and displays the difference between 2 dates in years/months/days. [1]: https://www.dunroaming.co.uk/timeline/new_page_1.htm – Steve Sharpe Dec 05 '20 at 09:00