D
D
Dmitry Maslennikov2017-03-29 17:26:40
JavaScript
Dmitry Maslennikov, 2017-03-29 17:26:40

How to calculate the exact difference between dates in years?

How to determine the exact difference in years between the current date and the date in the format "0000-00-00 00:00:00". In PHP this is easily solved:

DateTime::createFromFormat("Y-m-d H:i:s", '2014-09-12 00:00:00')
->diff(new DateTime('now'))
->y;


Is there a similar elegant solution in Java Script?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Maslennikov, 2017-03-29
@aprenoir

Final code. The input is a date in the format '0000-00-00 00:00:00', the output is the number of full years from the current date:

function age_count(date) {
    // now
    var now = new Date();
    now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
    now = now.toISOString().substr(0, 19).replace('T',' ');
    // calculate
    var age = now.substr(0, 4) - date.substr(0, 4);
    if(now.substr(5) < date.substr(5)) --age;
    // output
    return age;
}

PS If anyone knows how to more briefly bring the current date to the format '0000-00-00 00:00:00' - please write in the comments.

A
Adamos, 2017-03-29
@Adamos

var date1 = '2014-09-12 12:34:56';
var date2 = '2017-09-12 12:34:56';
if(date1.substr(5) == date2.substr(5) {
  alert('Господин программный архитектор, у вас день рождения наступило!');
} else {
  var years = date2.substr(0, 4) - date1.substr(0, 4);
  if(date2.substr(5) < date1.substr(5)) {
    --years;
  }
  alert('Вам таки ' + years + ' полных лет, а толку?');
}

S
Sergey Sokolov, 2017-03-29
@sergiks

We create two Date objects, birthday and now. To ensure that a date object is correctly obtained from a text string, you must first convert it to ISO 8601 format - the simplest is to replace the space with the letter "T". But such a date will be in the UTC time zone, you need to adjust it by adding minutes from getTimezoneOffset(). For example, the date "2014-09-12 00:00:00" Moscow time is September 11, 21:00 UTC. When comparing from "now", we will take UTC time - getUTCMonth(), etc.
Having received two dates, we compare their months, dates. If you need more accuracy, then also hours, minutes, seconds:

var sqlDT = "2014-09-12 00:00:00";
var BD = new Date( sqlDT.replace(' ','T'));
var Now = new Date();
BD.setMinutes( BD.getMinutes() + Now.getTimezoneOffset()); // в UTC

if( BD.getMonth() === Now.getUTCMonth()
  && BD.getDate() === Now.getUTCDate()
) {
  // ура! День рождения!
}

Ps An alternative option is to connect a hefty library for working with dates and times -  MomentJS , and find suitable methods in it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question