Auto Ad Code

Wednesday, October 20, 2010

Date difference in Javascript

This can be a need of people that they get instant difference between two dates without the postback. In .Net (C# or VB .Net) its pretty much easy and straight but in Javascript its not that much straight (Though is easy).
Anyways here is the solution. Following is the Javascript function calculating date difference in between two dates (give in two textbox named txtStartDate and txtEndDate) and will store the result (in days) in a textbox named txtDuration.

function calculateDuration()
{
var msInDay = 1000 * 60 * 60 * 24; //Milliseconds in a day
var startDateMS = new Date(document.getElementById("txtStartDate").value).getTime();
var endDateMS = new Date(document.getElementById("txtEndDate").value).getTime();
var differenceMS = Math.abs(endDateMS - startDateMS);
document.getElementById("txtDuration").value = Math.round(differenceMS/msInDay);
}

This function can be called like
<asp:TextBox ID="txtDuration" runat="server" onclick="javascript:calculateDuration();" onfocus="javascript:calculateDuration();"></asp:TextBox>

No comments:

Post a Comment