简体   繁体   中英

Calculate the difference between two dates set using Bootstrap Datepicker in terms of Years, Months and Days

I have three <input> tags in my code out of which two are populated with dates chosen from Bootstrap-Datepicker .

<input id="from-date" type="text" class="form-control" placeholder="From">
<input id="to-date" type="text" class="form-control" placeholder="To">
<input id="total-count" class="form-control" placeholder="Total no. of Years, Months and Days.">

I would like to calculate the difference between these two dates in terms of Years, Months and Days , and display it in total-count . I went through some examples on Stack Overflow, wasn't able to achieve/find an ideal solution, because it was really confusing to me. If anyone could help me solve this, it would be of great help.

Below is my JS code. I've updated the whole code Here

$(function() {

   // create the from date
   $('#from-date').datepicker({
     autoclose: true,
     format: 'dd-mm-yyyy',
   }).on('changeDate', function(ev) {
     ConfigureToDate();
   });


   $('#to-date').datepicker({
     autoclose: true,
     format: 'dd-mm-yyyy',
     startDate: $('#from-date').val()
   });

   // Set the min date on page load
   ConfigureToDate();

   // Resets the min date of the return date
   function ConfigureToDate() {
      $('#to-date').val("").datepicker("update");
      $('#to-date').datepicker('setStartDate', $('#from-date').val());
   }
}); 

You can use this concept:

var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());

var days = Math.floor(timeDiff / (1000 * 3600 * 24)); 
var months = Math.floor(days / 31);
varyears = Math.floor(months / 12);

Hope this will help you :)

If you're working with dates, there is no need to reinvent the wheel, Moment.js is a great library. ( https://momentjs.com/ )

Install/include the Moment.js on your page, then:

HTML:

<input id="from-date" type="text" class="form-control" placeholder="From">

<input id="to-date" type="text" class="form-control" placeholder="To">

<input id="total-count" class="form-control" placeholder="Total no. of Years, Months and Days.">
<br />
<br />
<input id="calculate" type="button" value="Calculate" />

JavaScript:

$(function() {

  $('#from-date').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy',
  });


  $('#to-date').datepicker({
    autoclose: true,
    format: 'dd-mm-yyyy'
  });

  $('#calculate').on('click', function() {

    var fromDate = moment($('#from-date').val(), 'DD-MM-YYYY');
    var toDate = moment($('#to-date').val(), 'DD-MM-YYYY'); 

    if (fromDate.isValid() && toDate.isValid()) {

      var duration = moment.duration(toDate.diff(fromDate));

      $('#total-count').val( duration.years() + ' Year(s) ' + duration.months() + ' Month(s) ' + duration.days() + ' Day(s)');

    } else {
        alert('Invalid date(s).')    

    }

  });


});

JSFiddle: ( http://jsfiddle.net/cvh2u2bk/ )

Working with dates I recommend you use a package like momentjs , it helps you with the pain using some date formats.

var date1 = moment('01/05/2017')
var date2 = moment('01/04/2017')

date1.diff(date2, 'days') //1
date1.diff(date2, 'months')//0
date1.diff(date2, 'years')//0

If you want to get an exact difference, you could add the flag variable

date1.diff(date2, 'months', true)//0.03225806451612903

More docs https://momentjs.com/docs/#/displaying/difference/

 $(function() { // create the from date $('#from-date').datepicker({ autoclose: true, format: 'dd-mm-yyyy', }).on('changeDate', function(ev) { ConfigureToDate(); }); $('#to-date').datepicker({ autoclose: true, format: 'dd-mm-yyyy', startDate: $('#from-date').val() }); // Set the min date on page load ConfigureToDate(); // Resets the min date of the return date function ConfigureToDate() { $('#to-date').val("").datepicker("update"); $('#to-date').datepicker('setStartDate', $('#from-date').val()); } $("input[name='to_date']").on('change', function() { var fromDate = moment($('#from-date').val(), 'DD-MM-YYYY'); var toDate = moment($('#to-date').val(), 'DD-MM-YYYY'); if (fromDate.isValid() && toDate.isValid()) { var duration = moment.duration(toDate.diff(fromDate)); $('#difference').val( duration.years() + ' Year(s) ' + duration.months() + ' Month(s) ' + duration.days() + ' Day(s)' ); } }); }); 
 input { cursor: pointer; } #difference { width: 210px; } 
 <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.standalone.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script> <input name="from_date" id="from-date" type="text" class="form-control" placeholder="From"> <input name="to_date" id="to-date" type="text" class="form-control" placeholder="To"> <input id="difference" class="form-control" placeholder="Total no. of Years, Months and Days."> 

Just in case if anyone needs a code that Dynamically( without a click event) updates/calculates the difference between two dates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM