Home > Uncategorized > Quick JavaScript: Test if a given string is a date

Quick JavaScript: Test if a given string is a date

This can be used with Protoplasm Datepicker, or other formats. I saw some very weird things to determine whether a string was a date, this seemed easy. I know people hate try…catch, but it works to validate something.

function checkdate(datetocheck)
{
try
{
	//check if datetocheck is a valid date by using Date.prase();
	//datetocheck is string 'MM-DD-YYYY HH:mm:ss'
	var month = +datetocheck.substring(0,2) - 1;
	var day = +datetocheck.substring(3,5);
	var year = +datetocheck.substring(6,10);
	var hour = +datetocheck.substring(11,13);
	var minute = +datetocheck.substring(14,16);
	var second = +datetocheck.substring(17,19);
	
	if(isNaN(month)) return false;
	if(isNaN(day)) return false;
	if(isNaN(year)) return false;
	if(isNaN(hour)) return false;
	if(isNaN(minute)) return false;
	if(isNaN(second)) return false;
	
	datetocheck = Date(year, month, day, hour, minute, second, 0);
	Date.parse(datetocheck);
	return true;
}
catch(err)
{
	//alert(err);
	return false;
}
}

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: