How to humanize javascript dates

Asked

Viewed 198 times

5

Given a date ex: 24/05/1982, how to transform into years, months and days? In the above example it would be converted into 33 years 1 month and 1 day. The idea is to do everything in Javascript.

  • You want to know the difference between the current date and the given date?

  • no, just convert it. Given a date, I want to convert it

  • Here he’s getting something else as an answer

3 answers

7


I advise you to use the plugin momentjs: Then it’s easy, just use the function Duration() to calculate the current time duration with the desired date:

var hoje = moment();
var dia  = moment("24-05-1982", "DD-MM-YYYY");
var duracao = moment.duration(hoje.valueOf()-dia.valueOf(), 'milliseconds');

document.getElementById("dias").innerHTML = duracao.years() + " anos, " + duracao.months() + " meses e " + duracao.days() + " dias.";
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<p id="dias"></p>

4

Using Moment.js is a good thing, but calculating the difference in milliseconds to then format the result in years, months and days is not.

When you ask Moment to format a millisecond amount for months/years, it assumes that each month has 30 days, returning a result that will hardly be expected.

In this edition of Moment.js one of the authors discourages the use of milliseconds to calculate the difference between dates: https://github.com/moment/moment/issues/1466

The best way is to calculate the units years, months and days separately:

var inicio = moment('24-05-1982', 'DD-MM-YYYY');
var agora = moment('2015-06-25');

var diferenca = moment.duration({
    years: agora.year() - inicio.year(),
    months: agora.month() - inicio.month(),
    days: agora.date() - inicio.date()
});

document.getElementById("anos").innerHTML = diferenca.years() + ' ano(s)';
document.getElementById("meses").innerHTML = diferenca.months() + ' mese(s)';
document.getElementById("dias").innerHTML = diferenca.days() + ' dia(s)';
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script>
<p>Se passaram <b id="anos"></b>, <b id="meses"></b> e <b id="dias"></b>.</p>

-2

It is not as simple as it seems to be. I have example in php.... Who knows you can not transpose the idea to javascript....

function dateDiff($dia1) {
// This is a simple script to calculate the difference between two dates
// and express it in years, months and days
// 
// use as in: "my daughter is 4 years, 2 month and 17 days old" ... :-)
//
// Feel free to use this script for whatever you want
// 
// version 0.1 / 2002-10-3
//
// please send comments and feedback to [email protected]
//

// ****************************************************************************

// configure the base date here
$d1 = explode('/', $dia1);
$base_day       = $d1[0];       // no leading "0"
$base_mon       = $d1[1];       // no leading "0"
$base_yr        = $d1[2];       // use 4 digit years!

// get the current date (today) -- change this if you need a fixed date
$current_day        = date ("j");
$current_mon        = date ("n");
$current_yr     = date ("Y");

// and now .... calculate the difference! :-)

// overflow is always caused by max days of $base_mon
// so we need to know how many days $base_mon had
$base_mon_max       = date ("t",mktime (0,0,0,$base_mon,$base_day,$base_yr));

// days left till the end of that month
$base_day_diff      = $base_mon_max - $base_day;

// month left till end of that year
// substract one to handle overflow correctly
$base_mon_diff      = 12 - $base_mon - 1;

// start on jan 1st of the next year
$start_day      = 1;
$start_mon      = 1;
$start_yr       = $base_yr + 1;

// difference to that 1st of jan
$day_diff   = ($current_day - $start_day) + 1;  // add today
$mon_diff   = ($current_mon - $start_mon) + 1;  // add current month
$yr_diff    = ($current_yr - $start_yr);

// and add the rest of $base_yr
$day_diff   = $day_diff + $base_day_diff;
$mon_diff   = $mon_diff + $base_mon_diff;

// handle overflow of days
if ($day_diff >= $base_mon_max)
{
    $day_diff = $day_diff - $base_mon_max;
    $mon_diff = $mon_diff + 1;
}

// handle overflow of years
if ($mon_diff >= 12)
{
    $mon_diff = $mon_diff - 12;
    $yr_diff = $yr_diff + 1;
}

// the results are here:

// $yr_diff     --> the years between the two dates
// $mon_diff    --> the month between the two dates
// $day_diff    --> the days between the two dates

// ****************************************************************************

// this is just to make it look nicer
$years = "anos";
$days = "dias";
$meses = "meses";
if ($yr_diff == "1") $years = "ano";
if ($day_diff == "1") $days = "dia";
if ($mon_diff=="1") $meses = "mês";

    // here we go
    $m = $d = "";
    if ($mon_diff > 0) {
        if ($day_diff > 0) {
            $m = ", $mon_diff $meses";      
        } else {
            $m = " e $mon_diff $meses";
        }
    }

    if ($day_diff > 0) {
        $d = " e $day_diff $days";
    }

    //return "$yr_diff $years, $mon_diff $meses e $day_diff $days";
    return "$yr_diff $years$m$d";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.