javascript学习指南|JavaScript之Date日期对象扩展的例子

更新时间:2020-09-04    来源:页面特效    手机版     字体:

【www.bbyears.com--页面特效】

一、前言

  JavaScript Date对象提供了诸多日期相关属性以及操作日期的相关方法,为开发网站带来了许多方便。然而,大部分web页面展示给用户的日期格式可能是这样:yyyy-MM-dd hh:mm:ss(类似于c# java的ToString())。

  不论是JavaScript Date对象的toString()方法,还是JavaScript Date对象的toGMTString()、toISOString()、toLocaleDateString()等方法,都无法转化成我们平时开发中想要的日期字符串格式;同时,关于日期相加减运算访求的封装,JavaScript Date对象也提供;那么,问题来了,我们平时编码过程中需要进行日期相关运算的时候,该怎么办呢?最佳途径就是,自己动手封装平时经常用到的日期处理函数,下面的代码就是本人在开发过程中封装的一些简单而用实用的日期处理函数。在未来的开发过程中,我会不断的完善、扩展及优化这些日期处理函数。

二、代码

 //名称:日期加法函数
 //参数:part(year、month、day、hour、minute、second、millisecond)
 //返回:Date对象
 Date.prototype.add = function (part, value) {
     if (!value || isNaN(value)) value = 0;
     switch (part) {
         case "year":
             this.setFullYear(this.getFullYear() + value);
             break;
         case "month":
             this.setMonth(this.getMonth() + value);
             break;
         case "day":
             this.setDate(this.getDate() + value);
             break;
         case "hour":
             this.setHours(this.getHours() + value);
             break;
         case "minute":
             this.setMinutes(this.getMinutes() + value);
             break;
         case "second":
             this.setSeconds(this.getSeconds() + value);
             break;
         case "millisecond":
             this.setMilliseconds(this.getMilliseconds() + value);
             break;
         default:
     }
     return this;
 };
 
 Date.prototype.addYears = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setFullYear(this.getFullYear() + value);
     return this;
 };
 
 Date.prototype.addMonths = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setMonth(this.getMonth() + value);
     return this;
 };
 
 Date.prototype.addDays = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setDate(this.getDate() + value);
     return this;
 };
 
 Date.prototype.addHours = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setHours(this.getHours() + value);
     return this;
 };
 
 Date.prototype.addMinutes = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setMinutes(this.getMinutes() + value);
     return this;
 };
 
 Date.prototype.addSeconds = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setSeconds(this.getSeconds() + value);
     return this;
 };
 
 Date.prototype.addMilliseconds = function (value) {
     if (!value || isNaN(value)) value = 0;
     this.setMilliseconds(this.getMilliseconds() + value);
     return this;
 };
 
 //名称:日期加法函数
 //参数:time(日期字符串,示例:12:00:00)
 //返回:Date对象
 Date.prototype.addTime = function (time) {
     var timeRegex = /^([0-1]?\d|2[0-3])(:[0-5]?\d){1,2}$/g;
     if (timeRegex.test(time)) {
         var value = Date.parse("1970/1/1 " + time) - Date.parse("1970/1/1");
         this.setMilliseconds(this.getMilliseconds() + value);
     }
     return this;
 };
 
 //名称:日期格式化函数
 //参数:format(示例:yyyy-MM-dd hh:mm:ss)、zeroize(是否补零)
 //返回:日期字符串
 Date.prototype.toCustomString = function (format, zeroize) {
     if (!zeroize) zeroize = false;
     var dy = this.getFullYear();
     var dM = this.getMonth() + 1;
     var dd = this.getDate();
     var dh = this.getHours();
     var dm = this.getMinutes();
     var ds = this.getSeconds();
     var dS = this.getMilliseconds();
     var orm = {
         "y+": dy.toString(),
         "M+": !zeroize ? dM.toString() : dM < 10 ? "0" + dM : dM.toString(),
         "d+": !zeroize ? dd.toString() : dd < 10 ? "0" + dd : dd.toString(),
         "h+": !zeroize ? dh.toString() : dh < 10 ? "0" + dh : dh.toString(),
         "m+": !zeroize ? dm.toString() : dm < 10 ? "0" + dm : dm.toString(),
         "s+": !zeroize ? ds.toString() : ds < 10 ? "0" + ds : ds.toString(),
         "S": dS.toString()
     };
     for (var i in orm) {
         var patt = new RegExp(i);
         if (patt.test(format)) {
             var item = orm[i];
             var ms = format.match(patt);
             var result = ms[0];
             if (i === "S") {
                 format = format.replace(result, item);
             } else {
                 format = format.replace(result, item.substr(item.length - result.length));
             }
         }
     }
     return format;
 };
View Code
三、分析
1.add函数:此函数的第一个参数提供了日期需要进行运算的部分(year、month、day、hour、minute、second、millisecond),返回日期对象;

2.add##函数:类似于addYear、addMonth、addDays等函数,即是对add函数的分解,为日期处理提供了更为方便快捷的功能;

3.addTime函数:此函数提供了日期对象类型与时间字符串类型运算的功能,time参数为时间字符串(示例:10:00:00);

4.toCustomString函数:此函数提供了日期对象类型转化成指定格式的日期字符串,format为日期格式化字符串参数(示例:yyyy-MM-dd hh:mm:ss);

以下示例中,示例1、示例2演示了add函数、add##函数的使用;示例3演示了addTime函数的使用。

三个示例中均用到toCustomString函数对结果进行格式化输出。


 //示例1:d1数据类型为整形,日期毫秒数
 var d1 = Date.now();
 var ret1 = new Date(d1).add("year", 2);//或者:var ret1 = new Date(d1).addYear(2);           
 console.log(ret1.toCustomString("yyyy-MM-dd hh:mm:ss"));
 //打印:2018-3-28 19:15:45
 
 //示例2:d2数据类型为字符串型,日期字符串
 var d2 = "2016-1-1 12:00:00";
 var ret2 = new Date(Date.parse(d2)).add("day", 10);//或者:var ret2 = new Date(Date.parse(d2)).addDays(10);           
 console.log(ret2.toCustomString("yyyy/MM/dd hh时mm分ss秒", true));
 //打印:2016/01/11 12时00分00秒
 
 //示例3:日期类型与时间字符串类型的运算
 var ret3 = new Date(Date.now()).addTime("2:10:00");
 console.log(ret3.toCustomString("yyyy-MM-dd hh:mm:ss", true));
 //打印:2016-03-28 21:25:45

看个例子 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 dt = new Date();
var nowDate = dt.format("yyyy-MM-dd hh:mm:ss");

就能得到当前的时间:2013-12-02 14:02:11

 

本文来源:http://www.bbyears.com/wangyetexiao/96576.html

热门标签

更多>>

本类排行