Thursday, May 15, 2008

Javascript Date Comparision using CustomValidator And String to Date Conversion using JavaScript

This function calculates the difference between the two Date, and Validate it,

I used this function to validate the difference between the From Date and To Date for not more then 366 days(to cover the leap year also) or less then 0,

This function is called through the CustomValidator of ASP.NET, but you can also use this without the CustomValidator.

<asp:CustomValidator runat="server" ID="custDateValidator"

ClientValidationFunction="CompareDates" Display="Dynamic"

ErrorMessage="The number of date to be included in report must be between 1 and 366">


This piece of code also depicts how we can convert the String to DateTime, because in my form I am taking the Dates from two HTML TextBoxes, which by default is String, so I had to write seperate piece of code which will convert String to DateTime.

<script language="JavaScript">

function CompareDates(source, args) {

var fromDate = new Date();

var txtFromDate = document.getElementById("txtDateFrom").value;

var aFromDate = txtFromDate.split("/");

/*Start 'Date to String' conversion block, this block is required because javascript do not provide any direct function to convert 'String to Date' */

var fdd = aFromDate[0]; //get the day part

var fmm = aFromDate[1]; //get the month part

var fyyyy = aFromDate[2]; //get the year part




var toDate = new Date();

var txtToDate = document.getElementById("txtDateTo").value;

var aToDate = txtToDate.split("/");

var tdd = aToDate[0]; //get the day part

var tmm = aToDate[1]; //get the month part

var tyyyy = aToDate[2]; //get the year part




//end of 'String to Date' conversion block

var difference = toDate.getTime() - fromDate.getTime();

var daysDifference = Math.floor(difference/1000/60/60/24);

difference -= daysDifference*1000*60*60*24;

//if diffrence is greater then 366 then invalidate, else form is valid

if(daysDifference > 366 daysDifference < 0)

args.IsValid = false;


args.IsValid = true;



I Hope this will Help.


Anonymous said...

Who knows where to download XRumer 5.0 Palladium?
Help, please. All recommend this program to effectively advertise on the Internet, this is the best program!

Post a Comment