Javascript Date - Usage, Calculation and Validation

From Code Trash
Jump to: navigation, search

Initializing date from server

<script type="text/javascript">
var _thisDay = <?=date('d')?>, _thisMonth = <?=date('m')-1?>, _thisYear = <?=date('Y')?>;
</script>


Comparing two dates

// date is stored in the form fields in the format dd-mm-yyyy
 
var fa = fom.fromdate.value.split('-')
var ta = fom.todate.value.split('-')
 
var a = new Date(fa[2],fa[1]-1,fa[0]);			
var d = new Date(ta[2],ta[1]-1,ta[0]);
 
var today = new Date(_thisYear,_thisMonth,_thisDay)
 
if(a>d)
{
	alert("From Date cannot be greater than To Date'");
	return false;
}
 
if(a.getTime()==d.getTime())
{
	alert("Dates cannot be equal'");
	return false;
}
 
if(a<today)
{
	alert("Please select a valid date'");
	return false;
}


Get number of days between two dates

function getDays(fromdate,todate)
{
	//here date is in the format yyyy-mm-dd
	fromdate = fromdate.split('-')
	todate = todate.split('-')
	var a = new Date(fromdate[0],fromdate[1]-1,fromdate[2]);			
	var d = new Date(todate[0],todate[1]-1,todate[2]);
	return  (d.getTime() - a.getTime())/86400000
}


Is date less than today - Is Old Date

// date format yyyy-mm-dd
 
function isOldDate(fa)
{
	if(typeof(fa)=='string')
		fa = document.getElementById(fa).value
	else fa = fa.value
 
	var fa = fa.split('-')
 
	var today = new Date(_thisYear,_thisMonth,_thisDay)	
 
	var a = new Date(fa[0],fa[1]-1,fa[2]);			
 
	if(a<today)
	{
		alert('Please select a future date');
		return true;
	}	
	return false;
}

Is date less than today II - Is Old Date II

// date format yyyy-mm-dd
 
function isOldDate(fa,splity)
{
	if(typeof(fa)=='string')
		fa = document.getElementById(fa).value
	else fa = fa.value
 
	var fa = fa.split(splity)
 
	var today = new Date(_thisYear,_thisMonth,_thisDay)	
 
	var a = new Date(fa[0],fa[1]-1,fa[2]);			
 
	if(a<today)
	{
		if(arguments.length>2 && arguments[2])alert(arguments[2])
		else alert('Please select a future date');
		return true;
	}	
	return false;
}

Is from date less than to date

// date format yyyy-mm-dd
 
function isLessDate(fa,ta)
{
	if(typeof(fa)=='string')
	{
		fa = document.getElementById(fa).value
		ta = document.getElementById(ta).value		
	}
	else
	{
		fa = fa.value
		ta = ta.value
	}
 
	var fa = fa.split('-')
	var ta = ta.split('-')
 
	var today = new Date(_thisYear,_thisMonth,_thisDay)	
 
	var a = new Date(fa[0],fa[1]-1,fa[2]);			
	var d = new Date(ta[0],ta[1]-1,ta[2]);
 
	if(a>d)
	{
		alert("From Date cannot be greater than To Date'");
		return true;
	}
	return false;
}