在Web前端开发中,与Date对象打交道算是很平凡的了,可以说是家常便饭了,所以日期对象是很常用的。这里,菜鸟写了个函数,把后台传过来的时间戳按规定的格式显示出来。其实很简单的,我们可以通过(Date(new Date())).toString()一句就可以得到一个格林威治时间格式字符串。
/** * @Descript: used to format Date like YYYY:MM:DD HH:MM:SS * @Date 2015-05-11 20:47:05 */
function formateDate(d) {
var date; //要处理的日期对象
if(!d) return;
if(typeof d == 'object') { //如果为日期对象
date = d;
}
if(typeof d == 'string') { //时间戳字符串
date = new Date(d);
}
var formate = function(h) {
return h < 10 ? '0' + h : h;
}
var year = date.getFullYear();
var month = formate(date.getMonth());
var day = formate(date.getDate());
var hour = formate(date.getHours());
var minute = formate(date.getMinutes());
var second = formate(date.getSeconds());
return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
}
/**---------- have test the function if it works --------**/
window.onload = function() {
var timeContainer = document.createElement('div');
var styleList = [
'text-align: center;',
'height: 100px;',
'line-height: 100px;',
'font-size: 24px;',
'font-family: Arail;',
'color: #ff2323;'
].join("");
timeContainer.style.cssText = styleList;
document.getElementsByTagName('body')[0].appendChild(timeContainer);
var getTime = function() {
setInterval(function(){
var date = new Date();
timeContainer.innerHTML = formateDate(date);
},1000);
};
getTime();
}