Skip to content Skip to sidebar Skip to footer

Converting A Date From DD-MM-YYYY To DD/MM/YYYY In Javascript And Finding The Difference

I am trying to convert a date (obtained from a datepicker field) in DD-MM-YYYY to DD/MM/YYYY and get the difference (in years) between the two.. I have tried this so far: function

Solution 1:

I am trying to convert a date (obtained from a datepicker field) in DD-MM-YYYY to DD/MM/YYYY

That can be done using a simple replace:

'21-04-2014'.replace(/-/g,'/'); // 21/04/2014

and get the difference (in years) between the two

How do you want to do that? Years can have 365 or 366 days, which should be used? Do you want the answer in decimal years, or years and days, or years, months and days?

The following function will calculate the difference between two dates in whole days. If you use the precise parameter, it will not round the days and will give the difference down to the millisecond. Note that it expects to be given Date objects, not strings.

See snippet below.

To convert a string in the format dd-mm-yyyy or dd/mm/yyyy you can use:

function parseDMY(s) {
  var b = s.split(/\D+/);
  return new Date(b[2], --b[1], b[0]);
}

To get the difference between say 1 January, 2012 and 22 July, 2014:

console.log(dateDifference(parseDMY('1-1-2012'), parseDMY('22-7-2014')));
// [2, 6, 21, 0, 0, "0.000"] or 2 years, 6 months, 21 days

And between 29 February, 2012 and 1 March, 2014 (leap years can be tricky):

console.log(dateDifference(parseDMY('29-2-2012'), parseDMY('1-3-2014')));
// [2, 0, 1, 0, 0, "0.000"] or 2 years, 0 months, 1 day

And between 31 January and 1 March 2014 (31 to 30 day months can be tricky too, simply adding one month to 31 Jan 2014 gives 3 March 2014):

console.log(dateDifference(parseDMY('31-1-2014'), parseDMY('1-3-2014')));
// [0, 1, 1, 0, 0, "0.000"] or 0 years, 1 month, 1 day

    // Given two date object, return the difference in years, months and days
    // Expects start date to be before end date
    // Default is to deal in whole days. For precise differences 
    // (hours, minutes and seconds), set precise to true
    function dateDifference(start, end, precise) {
      var timeDiff, years, months, days, hours, minutes, seconds;
    
      // Copy date objects so don't modify originals
      var s = new Date(+start);
      var e = new Date(+end);

      // If not precise, set h,m,s to zero
      if (!precise) {
        s.setHours(0,0,0,0);
        e.setHours(0,0,0,0);
      }
    
      // Get estimate of year difference
      years = e.getFullYear() - s.getFullYear();
    
      // Add difference to start, if greater than end, remove one year
      // Note start from restored start date as adding and subtracting years
      // may not be symetric
      s.setFullYear(s.getFullYear() + years);
      if (s > e) {
        --years;
        s = new Date(+start);
        s.setFullYear(s.getFullYear() + years);
      }

      // Allow for leap year: 29-Feb + 1 year -> 1-Mar
      if (start.getDate() != s.getDate()) {
        s.setDate(0);
      }
 
      // Get estimate of months
      months = e.getMonth() - s.getMonth();
      months += months < 0? 12 : 0;
    
      // Add difference to start, adjust if greater
      s.setMonth(s.getMonth() + months);

      if (s > e) {
        --months;
        s = new Date(+start);
        s.setFullYear(s.getFullYear() + years);
        s.setMonth(s.getMonth() + months);
      }

      // Allow for 31 day month rolling over to 1st
      if (start.getDate() != s.getDate()) {
        s.setDate(0);
      }

      // Get remaining time difference
      timeDiff = e - s;
      days     =  timeDiff / 8.64e7 | 0;
      hours    = (timeDiff % 8.64e7) / 3.6e6 | 0;
      minutes  = (timeDiff % 3.6e6) / 6e4 | 0;
      seconds  = ((timeDiff % 6e4) / 1e3).toFixed(3);
      return [years, months, days, hours, minutes, seconds];
    }

// Simple date string parser, doesn't validate values
function parseDMY(s) {
  var b = s.split(/\D/)
  return new Date(b[2], b[1]-1, b[0]);
}

function calcDiff(el) {
  var form = el.form;
  var start = parseDMY(form.startDate.value);
  var end   = parseDMY(form.endDate.value);
  if (isNaN(start) || isNaN(end)) return;
  var diff = dateDifference(start, end);
  document.getElementById('output').innerHTML = diff[0] + ' year'  + (diff[0] == 1? ' ' : 's ') +
                                                diff[1] + ' month' + (diff[1] == 1? ' ' : 's ') +
                                                diff[2] + ' day'   + (diff[2] == 1? '' : 's');
}
<form id="f">
  <table>
    <tr><td>Start date (d/m/y)<td><input name="startDate" value="20/03/2016">
    <tr><td>End date (d/m/y)<td><input name="endDate" value="20/04/2017"> 
    <tr><td><input type="reset"><td><input type="button" onclick="calcDiff(this)" value="Get difference">
  </table>
</form>
<div id="output"></div>      
      

This still has a few issues for leap years, update on the way…


Solution 2:

Try to make two Date- Objects like this

var date1 = new Date(2010, 6, 17);
var date2 = new Date(2013, 12, 18);
var diff = new Date(date2.getTime() - date1.getTime());

console.log(diff.getUTCFullYear() - 1970); // Gives difference as year
// 3

console.log(diff.getUTCMonth()); // Gives month count of difference
// 6

console.log(diff.getUTCDate() - 1); // Gives day count of difference
// 4

Post a Comment for "Converting A Date From DD-MM-YYYY To DD/MM/YYYY In Javascript And Finding The Difference"