﻿//ConvertDate - Converts a date given in GMT to the specified string
function ConvertDate(strDate, strFormat)
{
	return FormatDate(new Date(strDate), strFormat);
}

//LeadingZero - Gives a leading zero to a single digit number
function LeadingZero(strNumber)
{
	return (strNumber < 0 || strNumber > 9 ? "" : "0") + strNumber;
}

//FormatDate - Formats a date based in the input format
function FormatDate(dteDate, strFormat) {
	strFormat = strFormat + "";

	var strMonthNames = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
	var strResult = "";
	var intPosition = 0;
	var charCheck = "";
	var strToken = "";
	var strYear = dteDate.getYear() + "";
	var strMonth = dteDate.getMonth() + 1;
	var strDay = dteDate.getDate();
	var strHour = dteDate.getHours();
	var strMinute = dteDate.getMinutes();
	var strSecond = dteDate.getSeconds();
	var objValue = new Object();

	if (strYear.length < 4)
	{
		strYear= "" + (strYear - 0 + 1900);
	}
	objValue["y"] = "" + strYear;
	objValue["yyyy"] = strYear;
	objValue["yy"] = strYear.substring(2, 4);
	objValue["M"] = strMonth;
	objValue["MM"] = LeadingZero(strMonth);
	objValue["MMM"] = strMonthNames[strMonth + 11];
	objValue["MMMM"] = strMonthNames[strMonth - 1];
	objValue["d"] = strDay;
	objValue["dd"] = LeadingZero(strDay);

	objValue["H"] = strHour;
	objValue["HH"] = LeadingZero(strHour);
	if (strHour == 0)
		objValue["h"] = 12;
	else if (strHour > 12)
		objValue["h"] = strHour - 12;
	else
		objValue["h"] = strHour;
	objValue["hh"] = LeadingZero(objValue["h"]);
	if (strHour > 11)
		objValue["K"] = strHour - 12;
	else
		objValue["K"] = strHour;
	objValue["k"] = strHour + 1;
	objValue["KK"] = LeadingZero(objValue["K"]);
	objValue["kk"] = LeadingZero(objValue["k"]);

	if (strHour > 11)
		objValue["a"] = "PM";
	else
		objValue["a"] = "AM";

	objValue["m"] = strMinute;
	objValue["mm"] = LeadingZero(strMinute);
	objValue["s"] = strSecond;
	objValue["ss"] = LeadingZero(strSecond);

	while (intPosition < strFormat.length) {
		charCheck = strFormat.charAt(intPosition);
		strToken="";

		while ((strFormat.charAt(intPosition) == charCheck) && (intPosition < strFormat.length))
			strToken += strFormat.charAt(intPosition++);

		if (objValue[strToken] != null)
			strResult = strResult + objValue[strToken];
		else
			strResult = strResult + strToken;
	}
	return strResult;
}
