0

There are two datetime fields, which are filled by the user. I need to calculate the difference between them in hours, days and months. All examples I found are with dates that are entered in JavaScript or JQuery, but not from user input. My code is not working. I think I use the selection wrong.


    function getDD () {
    var adate = $(document.querySelector('input[id="d04"]').value);
    var adatems = adate.getTime();

    var odate  = $(document. querySelector('input[id="o02"]').value);
    var odatems = odate.getTime();

    var hms = 3600000;
    var dms = 86400000;
    var mms = 2628002880;

    var difOA = odatems - adatems;

    var oah = Math.round(difOA / hms);
    var oad = Math.round(difOA / dms);
    var oam = Math.round(difOA / mms);

    $('#r1').val((oah));
    $('#r2').val((oad));
    $('#r3').val((oam));
    }

    $(document).ready(function() {
    $('input[name= a_date]').blur(function(e) {
    $('#r1; r2; r3').val());
    getDD();
    $('input[name= o_date]').blur(function(e) {
    $('#r1; r2; r3').val());
    getDD();
    });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="d04" type="datetime-local" name="a_date">a_date
    <br />

    <input id="o02" type="datetime-local" name="o_date">o_date
    <br />

    <input id="r1" type="text" name="o-a_ hours" readonly="true" placeholder="Diff in Hours"/>o-a_hours
    <br />

    <input id="r2" type="text" name="o-a_ days" readonly="true" placeholder="Diff in days"/>o-a_days 
    <br />

    <input id="r3" type="text" name="o-a_ months" readonly="true" placeholder="Diff in months"/>o-a_months  
    <br />
M0ns1f
  • 2,705
  • 3
  • 15
  • 25
pap
  • 123
  • 1
  • 2
  • 14
  • Would you mind using an external library to help you with that? – PlayMa256 Nov 07 '17 at 21:22
  • I don’t mind. I need a solution :) – pap Nov 07 '17 at 21:22
  • 1
    Try moment.js, you can do pretty much anything time/date related with that. – PlayMa256 Nov 07 '17 at 21:23
  • @MatheusSilva this doesn’t help much. I Know about moments.js, but how to use it? – pap Nov 07 '17 at 21:26
  • @JonUleis well I’m not a pro... I appreciate your remark, but I also need a direction – pap Nov 07 '17 at 21:28
  • There are a zillion stack overflow questions featuring moment.js which have code examples. [This one](https://stackoverflow.com/questions/36600687/moment-js-two-dates-difference-in-number-of-days) seems to be relevant. – James Nov 07 '17 at 21:29
  • Probably a duplicate of [*How to get the difference of two dates in mm-dd-hh format in Javascript*](https://stackoverflow.com/questions/35504942/how-to-get-the-difference-of-two-dates-in-mm-dd-hh-format-in-javascript). – RobG Nov 08 '17 at 01:18

0 Answers0