Get the Number of Years Between Two Dates with PHP and JavaScript
Working with dates is a pretty common task for web developers, especially developers working with dynamic content or content management systems. Often this just involves accepting a DateTime object and formatting it to appear a certain (more human‑readable) way. However, there can be much more advanced use cases ‑ for instance when building a blog and showing dates in time‑since format: "1 year ago", "2 years ago", etc.
This is exactly what I do here on my own website to generate my Timeline page where I use Twitter and the #todayi hashtag to offer brief insights into my working day‑to‑day. I've also toyed with the idea of changing my blog to display dates in this format.
So in this article, we are going to take a look at how to get the number of years between two dates, both via the back‑end with PHP and client side in Javascript.
PHP
So, to do this in PHP let's grab today's date using the DateTime class, and figure out the years between today and the 1st of January in the year 2000:
<?php $today = new DateTime(); $millennium = new DateTime('2000-01-01'); $years_between = $millennium -> diff($today); echo $years_between -> y;?>At the time of writing, this will return 14. Easy!
JavaScript
So let's take a look at doing this in JavaScript. It's a little trickier, and there are a lot of recommendations to just use libraries like moment.js (which, at over 2KB, is a pretty big dependency for what should be quite a simple operation), but here's a way to do this with just vanilla JS:
function years_between(dateFrom, dateUntil) { var diff = (dateFrom.getTime() - dateUntil.getTime()) / 1000; diff /= 60 * 60 * 24; var rounded = Math.abs(diff / 365) | 0; return rounded;}var millennium = new Date('January 1 2000');var today = new Date();console.log(years_between(millennium, today));With JavaScript, the Date objects represent the number of milliseconds since 1st January 1970 UTC (this is known as Epoch or Unix time). So, here what we're doing is figuring out the difference between the two dates in milliseconds, then dividing that number by the number of hours in a day. Then we're dividing that by the number of days in a year and rounding that down to get the expected answer of 14.
This is a much longer walk to get to the same place we achieved with four lines of PHP, but still very achievable nevertheless. There are a few minor complications if you are dealing with dates before 1970 (where Date should return a negative number), but for most use cases, the snippet above is all you need.