Tuesday, December 17, 2013

Java Script : Date Format Utilities

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
Date.prototype.monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];

Date.prototype.getMonthName = function() {
return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
return this.getMonthName().substr(0, 3);
};

function convert(dateObj,fromFormat,toFormat) {
/*default the values 
dateObj default it to new Date();
fromFormat default it to UTC;
toFormat default it to UTC;
*/
var dateObj = dateObj;
var fromFormat = fromFormat;
var toFormat = toFormat;
if(!dateObj || dateObj=="")
dateObj = new Date();
debugger;
//if both fromFormat and toFormat is null
dateObj = new Date(Date.parse(dateObj));
if(!toFormat || toFormat=='' || toFormat=='CORDYS')
{
//return the dateObj in UTC Format
return dateObj.toISOString();
}
if(toFormat=='dd-MM-yyyy'){
var formattedDT = dateObj.getDate()+"-"+dateObj.getMonth()+"-"+dateObj.getFullYear();
return formattedDT;
}
if(toFormat=='yyyy-MM-dd'){
var formattedDT = dateObj.getFullYear()+"-"+dateObj.getMonth()+"-"+dateObj.getDate();
return formattedDT;
}
if(toFormat=='UTC'||toFormat=='GMT'){
return dateObj.toUTCString();
}
if(toFormat=='dd/MM/yyyy'){
var formattedDT = dateObj.getDate()+"/"+dateObj.getMonth()+"/"+dateObj.getFullYear();
return formattedDT;
}
if(toFormat=='yyyy/MM/dd'){
var formattedDT = dateObj.getFullYear()+"/"+dateObj.getMonth()+"/"+dateObj.getDate();
return formattedDT;
}
if(toFormat=='dd-MMM-yyyy'){
var formattedDT = dateObj.getDate()+"-"+dateObj.getShortMonthName()+"-"+dateObj.getFullYear();
return formattedDT;
}
if(toFormat=='dd MMM yyyy'){
var formattedDT = dateObj.getDate()+" "+dateObj.getShortMonthName()+" "+dateObj.getFullYear();
return formattedDT;
}
var format = dateObj.getFullYear()+"-";
format += dateObj.getMonth()+"-";
format += dateObj.getDate();
return dateObj.toJSON();
}
function convertDate(){
$("#convertedFormat").html(convert($('#custDate').val(),'',$('#ipDateFormat').val()));
}
</script>
</head>
<body>
<font style="font-family:Trebuchet MS;font-size:14px;width:100%;">Date Format <input id="ipDateFormat"></input></font><br/>
<input id="custDate" type="date" title="Please enter Date"></input><br/>
<button id="convertFormat" onclick="convertDate()">Convert Format</button><br/>
<div id="convertedFormat" style="font-family:Trebuchet MS;font-size:14px;width:100%;"><div>
</body>
</html>

No comments:

Post a Comment