js/jq基础(日常整理记录)-1-纯js格式化时间

一、纯js格式化时间

 之前记录了一些,工作中发现的比较常用的使用,就记录一下。

由于很基础,就直接贴出来了,不做分析了。

改造一下Date的原型

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; 
}  

 看看如何使用吧。 

//使用方法 
var now = new Date(); 
var nowStr = now.format("yyyy-MM-dd hh:mm:ss"); 

//使用方法2: 
var testDate = new Date(); 
var testStr = testDate.format("YYYY年MM月dd日hh小时mm分ss秒"); 
alert(testStr); 
//示例: 
console.log(new Date().format("yyyy年MM月dd日"));
console.log(new Date().format("MM/dd/yyyy"));
console.log(new Date().format("yyyyMMdd"));
console.log(new Date().format("yyyy-MM-dd hh:mm:ss"));

看看执行的结果吧。

还是蛮好用的吧,把这段简短的js代码放置到公共的js文件中,以后直接使用就可以啦,就不用自己去转化了哈。

原文地址:https://www.cnblogs.com/newwind/p/8920469.html