2011年9月30日 星期五

Javascript switch UTC Date to local time



Date.prototype.formatDate = function(format)
{
var date = this;
if (!format)
format="MM/dd/yyyy";

var month = date.getMonth() + 1;
var year = date.getFullYear();

format = format.replace("MM",month.toString().padL(2,"0"));

if (format.indexOf("yyyy") > -1)
format = format.replace("yyyy",year.toString());
else if (format.indexOf("yy") > -1)
format = format.replace("yy",year.toString().substr(2,2));

format = format.replace("dd",date.getDate().toString().padL(2,"0"));


var hours = date.getHours();
var hasAMPM = false;
if (format.indexOf("t") > -1)
{
hasAMPM = true;
if (hours > 11)
format = format.replace("t","pm")
else
format = format.replace("t","am")
}

if (format.indexOf("hh") > -1) {
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12;
format = format.replace("hh",hours.toString().padL(2,"0"));
}
if (format.indexOf("HH") > -1) {
if(!hasAMPM) {
format = format.replace("HH",hours.toString().padL(2,"0"));
} else {
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12;
format = format.replace("HH",hours.toString().padL(2,"0"));
}
}
if (format.indexOf("mm") > -1)
format = format.replace("mm",date.getMinutes().toString().padL(2,"0"));
if (format.indexOf("ss") > -1)
format = format.replace("ss",date.getSeconds().toString().padL(2,"0"));

if(format.indexOf("O") > -1)
format=format.replace("O",(date.getTimezoneOffset() < 0 ? '-' : '+') + (date.getTimezoneOffset() / 60 < 10 ? '0' : '') + (date.getTimezoneOffset() / 60) );

return format;
}




沒有留言:

wibiya widget