JS Date-parser

Alxandr 0 Tallied Votes 325 Views Share

This is a simple code-snippet that can be used to parse dates with javascript. It's setup to use European dates (dd.mm.yyyy | dd/mm/yyyy | dd,mm,yyyy), but it can easily be setup to use american dates as well (mm/dd/yyyy etc), to do so simply replace "$1" with "$2" and "$2" with "$1".

No framework should be required for this code to run.

/* Use: this file parses a date in the format "dd.mm.yyyy" into a JS Date-object.
 * It exposes several functions. The first one is parseDate(string), it returns a
 * date representation of a string-object. If the string does not match the
 * required format null is returned. Second is the toDate on the string object.
 * this is just a wrapper for the parseDate method so that you can call
 * "24.10.09".toDate();. Third is the stripPrecedingZeroes-helper method. It's
 * used to strip away 0's at the beginning of a string (example "009"->"9").
 * The isDate only checks to see wheater or not a string is a valid date.
 *
 * @author: Alxandr
 */
function parseDate(input)
{
	// regex: /^(\d{1,2})[\.,/](\d{1,2})([\.,/](\d{1,4})?)?$/
	var regex = new RegExp("^(\\d{1,2})[\\.,/](\\d{1,2})([\\.,/](\\d{1,4})?)?$");
	var Trim = function(string)
	{
		return string.replace(/^\s+|\s+$/g, '');
	}
	var fixYear = function(string)
	{
		var intVal = parseInt(string);
		if(intVal > 100) return intVal.toString();
		if(intVal >= 70) return "19" + intVal.toString();
		if(intVal >= 10) return "20" + intVal.toString();
		return "200" + intVal.toString();
	}
	try
	{
		var dato = Trim(input);
		if(dato.match(regex))
		{
			var date = dato.replace(regex, "$1").stripPrecedingZeroes();
			var month = dato.replace(regex, "$2").stripPrecedingZeroes();
			var year = fixYear((dato.replace(regex, "$4") || new Date().getFullYear().toString()).stripPrecedingZeroes());
			var d = new Date();
			d.setFullYear(parseInt(year));
			d.setMonth(parseInt(month) - 1);
			d.setDate(parseInt(date));
			if(!(d.getFullYear().toString() == year && (d.getMonth() + 1).toString() == month && d.getDate() == date))
			{
				throw new Error();
			}
			return d;
		}
	}
	catch (e)
	{
		return null;
	}
}
String.prototype.toDate = function()
{
	return parseDate(this);
}
String.prototype.stripPrecedingZeroes = function()
{
	var i = 0;
	while(this.charAt(i) == "0")
	{
		i++;
	}
	return this.substring(i);
}
function isDate(string)
{
	return !!parseDate(string);
}
Date.parseDate = parseDate;
String.prototype.isDate = function()
{
	return isDate(this);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.