0

Suppose I have 5 text-boxes respectively For Start Date, Start Time, End Date, End time & another Text box For Showing the Result all inside a Grid View in asp.net. I want to Calculate the difference between the two dates along with the time also for key up event of the End time text box & show it into the text box which is used for Showing Result.

My Input will be like this:

For Date 20/08/2014 For Time : 17:55

I am new to j query & unable to search the exact or similar solution for my problem. Can any one help here? Thanks in advance.

var start = $('#start_date').val();
var end = $('#end_date').val();

// end - start returns difference in milliseconds 
var diff = new Date(end - start);

// get days
var days = diff/1000/60/60/24;

Example

var start = new Date("2010-04-01"),
    end   = new Date(),
    diff  = new Date(end - start),
    days  = diff/1000/60/60/24;

days; //=> 8.525845775462964

Got Above Solution from stack overflow itself but this is not like exactly mine. i have date & time both in separate text boxes.

Santanu Maulik
  • 111
  • 2
  • 12

2 Answers2

1

moment.js is a great idea

$( "#endtime" ).keyup(function() {
var startdt = new Date($("#startdate").val() + " " + $("#starttime").val());

var enddt = new Date($("#enddate").val() + " " + $("#endtime").val());

var diff = enddt - startdt;

var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -=  days * (1000 * 60 * 60 * 24);

var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);

var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);

var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);

$("#result").val(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");

})

here you can find this working sample jsfiddle example

I wrote it "on fly" , so it could be not really elegant but works.

Be sure to check the validity of your input values

Luca
  • 1,588
  • 2
  • 22
  • 26
0

You can use the moment.js library. It can easily do a lot of operations with date and time.

Look at this SO Q&A:

Get the time difference between two datetimes

Community
  • 1
  • 1
JotaBe
  • 38,030
  • 8
  • 98
  • 117