获取时间函数

在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();
}  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值