Javascript里格式化时间函数

  • 内容
  • 评论
  • 相关

最近在学习javascript,因为在玩一个小游戏,利用js编了个小外挂(这个后面整理好了以后再和大家分享),需要显示当前连接的日期与时间记录,开始用的是这样的方法:

var myDate = new Date();
var showtime=myDate.getFullYear()+"-"+(myDate.getMonth()+1)+"-"+myDate.getDate()+" "+myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds();

但是发现显示并不整齐,譬如秒只有1位的时候,就显示1位,这样日志下来就不好看了,希望都是2位的格式,整整齐齐的。
后来再搜索试验了一下,找到另外一个简单好用的表示方法,格式整齐,现和大家分享一下:

/*
* 时间对象的格式化;
eg: alert((new Date()).format("yyyy年MM月dd日hh小时mm分ss秒"));
简单格式可以这样:showtime = new Date().format("yyyy-MM-dd hh:mm:ss");
*/
Date.prototype.format = function(format)
{
    var o = {
        "M+" :  this.getMonth()+1,  //month
        "d+" :  this.getDate(),     //day
        "h+" :  this.getHours(),    //hour
        "m+" :  this.getMinutes(),  //minute
        "s+" :  this.getSeconds(), //second
        "q+" :  Math.floor((this.getMonth()+3)/3),  //quarter
        "S"  :  this.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(format)) 
    {
        format = format.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
    }
    for(var k in o) 
    {
        if(new RegExp("("+ k +")").test(format)) 
        {
            format = format.replace(RegExp.$1, RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
        }
    }
    return format;
}

摘自:
http://www.iteye.com/topic/183162
和:
http://www.iteye.com/topic/579918 的评论

其实里面还有很多不懂,先用了,以后再慢慢消化吧.

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据