7

I have two input fields to enter date, which is a jquery datepicker. Using that I can select dates. They are check in and check out dates.

Similarly I have two select box, from which I can select the time. They are check in and check out time.

Eg:

Check in date: 01/05/2014
Check in time: 13:00


Check out date: 04/05/2014
Check out time: 18:00

I want the result: Difference between (01/05/2014 13:00) and (04/05/2014 18:00) like 3days 5 hrs

Fiddle

Right now I am getting the result NAN

Following is the script I am using:

$(document).ready(function(){
    $("#diff").focus(function(){
        var start = new Date($('#din').val());
        var end = new Date($('#dou').val());
        var diff = new Date(end - start);
        var days = Math.floor(diff/1000/60/60/24);
        var hours = Math.floor((diff % ( 1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
         $("#diff").val(days+' Day(s) '+hours+' Hour(s)');
    });
});
Leo T Abraham
  • 2,407
  • 4
  • 28
  • 54

3 Answers3

1

Fiddle Demo

$(document).ready(function () {
    function ConvertDateFormat(d, t) {
        var dt = d.val().split('/'); //split date
        return dt[1] + '/' + dt[0] + '/' + dt[2] + ' ' + t.val(); //convert date to mm/dd/yy hh:mm format for date creation.
    }
    $("#diff").focus(function () {
        var start = new Date(ConvertDateFormat($('#din'), $('#tin')));
        var end = new Date(ConvertDateFormat($('#dout'), $('#tout')));
        console.log(start, end);
        var diff = new Date(end - start);
        var days = Math.floor(diff / 1000 / 60 / 60 / 24);
        var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / 1000 / 60 / 60);
        $("#diff").val(days + ' Day(s) ' + hours + ' Hour(s)');
    });
});


ConvertDateFormat(d,t) converts the date to current format.

to get new Date('mm/dd/yy hh:mm')


Date
Update

Problem

Typo

var end = new Date($('#dout').val());
//                         ^ missing t in id it's dout not dou

which makes date invalid so you get NaN when you subtract invalid Date .

Updated Fiddle Demo With your code

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
  • 1
    It might help the asker (and future readers) more if you include an explanation of what you did and why it fixes the problem, instead of just dumping code :) – Michelle May 01 '14 at 12:36
  • In between I found my error. But the date format was troubling me. But you have cleared it :-) – Leo T Abraham May 01 '14 at 12:38
  • when i selected CheckIn: 02/05/2014, CheckOut: 02/05/2014, Time in: 13:00, Time out: 12:00, It gives Difference: 0 Day(s) 1 Hour(s) !!!, But i think it should be 0 Day(s) -1 Hour(s) – Ashok Damani May 01 '14 at 13:00
  • @TusharGupta: When trying [**your fiddle**](http://jsfiddle.net/cse_tushar/6He6f/) from the answer, I select `01/05/2014` and `02/05/2014` - `13:00` and `12:00` I get `1 Day(s) 1 Hour(s)` though it should be `0 Day(s) 23 Hour(s)` Not sure what is causing this. I'm in Ireland and on GMT time zone. Maybe it is that custom date formatting conversion. Not sure though. It is not needed anyway as jQuery datepicker has a native way of returning the date object already and the date object has a native way of setting the hours. – Nope May 01 '14 at 22:01
  • @TusharGupta: I found why, the value of the time option for `12:00` is set to `02:00` in the code, hence it only uses `2` instead of `12`. Now it works when selecting `01/05/2014` and `02/05/2014` - `13:00` and `12:00` I get `0 Day(s) 23 Hour(s)`. Though it goes bonkers on the negatives: `01/05/2014` and `01/05/2014` - `13:00` and `12:00` I get `-1 Day(s) -1 Hour(s)` if it should only be `0 Day(s) -1 Hour(s)` (I had the same issue and was only able to work around this ensuring to always deduct lesser from larger then manually adding `-` in the text if wanted. – Nope May 01 '14 at 22:31
1

You can use the datepicker native getDate feature to get the date object. Then using the information from this SO answer in regards to taking daylight savings into account you can use UTC date times to get the exact differences.

In addition to make setting the date time extremely simple, if you can change the value of your options, set them to the actual hour values, similar to this:

<select id="tin" name="tin">
    <option value="13">13:00</option>
    <option value="19">19:00</option>
</select>

and this

<select id="tout" name="tout">
    <option value="12">12:00</option>
    <option value="18">18:00</option>
</select>

That will make the code so easy using only native date object features to calculate your dates and times, except when dividng by 24 to get the days from the hours, similar to this:

var _MS_PER_HOUR = 1000 * 60 * 60; // 3600000ms per hour
var outputTextWithSign = '{0}{1} Days(s) {2}{3} Hours(s)'; // included sign
var outputTextWithoutSign = '{0} Days(s) {1} Hours(s)'; // no sign

$(function () {
    $("#din, #dout").datepicker({
        minDate: 0,
        dateFormat: 'dd/mm/yy'
    });
});

$(document).ready(function () {
    $("#diff").focus(function () {
        var startDate = $('#din').datepicker('getDate');
        var endDate = $('#dout').datepicker('getDate');

        // use native set hour to set the hours, assuming val is exact hours
        // otherwise derive exact hour from your values
        startDate.setHours($('#tin').val());
        endDate.setHours($('#tout').val());

        // convert date and time to UTC to take daylight savings into account
        var utc1 = Date.UTC(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), startDate.getHours(), startDate.getMinutes(), startDate.getSeconds());
        var utc2 = Date.UTC(endDate.getFullYear(), endDate.getMonth(), endDate.getDate(), endDate.getHours(), endDate.getMinutes(), endDate.getSeconds());

        // get utc difference by always deducting less from more
        // that way you always get accurate difference even if in reverse!
        var utcDiff = utc1 > utc2 ? utc1 - utc2 : utc2 - utc1;

        // get total difference in hours
        var msDiff = Math.floor(utcDiff / _MS_PER_HOUR);

        // get days from total hours
        var dayDiff = Math.floor(msDiff / 24);

        // get left over hours after deducting full days
        var hourDiff = Math.floor((msDiff - (24 * dayDiff)));

        //
        // write out results
        //

        // if you really need to show - sign and not just the difference...
        var sign = utc1 > utc2 ? '-' : '';

        // format output text - with (-)sign if required
        var txtWithSign = outputTextWithSign.format(dayDiff ? sign : '', dayDiff, hourDiff ? sign : '', hourDiff);

        // simple format without sign
        var txtNoSign = outputTextWithoutSign.format(dayDiff, hourDiff);

        // assign result - switch with/without sign result as needed
        $("#diff").val(txtWithSign);
        //$("#diff").val(txtNoSign);
    });
});

// Helper for easy string formatting.
String.prototype.format = function () {
    //var s = arguments[0];
    var s  = this;

    for (var i = 0; i < arguments.length; i++) {
        var reg = new RegExp("\\{" + i + "\\}", "gm");
        s = s.replace(reg, arguments[i]);
    }

    return s;
}

DEMO - Get Day and Hour difference, taking daylight savings into account


Community
  • 1
  • 1
Nope
  • 22,147
  • 7
  • 47
  • 72
  • i would Vote ur answer instead of accepted answer (@Tushar Gupta's) as i commented on his answer. – Ashok Damani May 01 '14 at 13:09
  • @AshokDamani: I read your comment on the -1 hour and had to look at my code. It took me some time to work out as for some reason when deducting `utc2 - utc1` when `utc1` was bigger the results went all weird. I'm sure there is a better way but I calculated the differences in the end by always deducting smaller from larger and added the `-` if needed in the end. I included both options now for either including a `-` sign or not. Also added handy formatting function. The code should now work for all scenarios. – Nope May 01 '14 at 22:11
0

use jQuery datePicker to pick dates

and for difference try this one..

html

<input type="text" id="date1">
<input type="text" id="date2">
<input type="text" id="calculated">


$(document).ready(function () {

var select=function(dateStr) {
      var d1 = $('#date1').datepicker('getDate');
      var d2 = $('#date2').datepicker('getDate');
      var diff = 0;
      if (d1 && d2) {
            diff = Math.floor((d2.getTime() - d1.getTime()) / 86400000); // ms per day
      }
      $('#calculated').val(diff);
}

$("#date1").datepicker({ 
    minDate: new Date(2012, 7 - 1, 8), 
    maxDate: new Date(2012, 7 - 1, 28),
    onSelect: select
});
$('#date2').datepicker({onSelect: select});
});
Sach
  • 554
  • 5
  • 14