首页  ·  知识 ·  前端
Javascript关于日期的各种技巧和方法总结
佚名  http://www.cnblogs.com/goody9807/  综合  编辑:dezai  图片来源:网络
script language="javascript"!--function PowerDate(timeString){this.date=null;if(timeString!="") this.date=new Date



 

/**//*
******************************************
日期函数扩充
******************************************
*/


/**//*
===========================================
//转换成大写日期(中文)
===========================================
*/
Date.prototype.toCase = function()
{
var digits= new Array('零','一','二','三','四','五','六','七','八','九','十','十一','十二');
var unit= new Array('年','月','日','点','分','秒');

var year= this.getYear() + "";
var index;
var output="";

////////得到年
for (index=0;index{
output += digits[parseInt(year.substr(index,1))];
}
output +=unit[0];

///////得到月
output +=digits[this.getMonth()] + unit[1];

///////得到日
switch (parseInt(this.getDate() / 10))
{
case 0:
output +=digits[this.getDate() % 10];
break;
case 1:
output +=digits[10] + ((this.getDate() % 10)>0?digits[(this.getDate() % 10)]:"");
break;
case 2:
case 3:
output +=digits[parseInt(this.getDate() / 10)] + digits[10]  + ((this.getDate() % 10)>0?digits[(this.getDate() % 10)]:"");
default:

break;
}
output +=unit[2];

///////得到时
switch (parseInt(this.getHours() / 10))
{
case 0:
output +=digits[this.getHours() % 10];
break;
case 1:
output +=digits[10] + ((this.getHours() % 10)>0?digits[(this.getHours() % 10)]:"");
break;
case 2:
output +=digits[parseInt(this.getHours() / 10)] + digits[10] + ((this.getHours() % 10)>0?digits[(this.getHours() % 10)]:"");
break;
}
output +=unit[3];

if(this.getMinutes()==0&&this.getSeconds()==0)
{
output +="整";
return output;
}

///////得到分
switch (parseInt(this.getMinutes() / 10))
{
case 0:
output +=digits[this.getMinutes() % 10];
break;
case 1:
output +=digits[10] + ((this.getMinutes() % 10)>0?digits[(this.getMinutes() % 10)]:"");
break;
case 2:
case 3:
case 4:
case 5:
output +=digits[parseInt(this.getMinutes() / 10)] + digits[10] + ((this.getMinutes() % 10)>0?digits[(this.getMinutes() % 10)]:"");
break;
}
output +=unit[4];

if(this.getSeconds()==0)
{
output +="整";
return output;
}

///////得到秒
switch (parseInt(this.getSeconds() / 10))
{
case 0:
output +=digits[this.getSeconds() % 10];
break;
case 1:
output +=digits[10] + ((this.getSeconds() % 10)>0?digits[(this.getSeconds() % 10)]:"");
break;
case 2:
case 3:
case 4:
case 5:
output +=digits[parseInt(this.getSeconds() / 10)] + digits[10] + ((this.getSeconds() % 10)>0?digits[(this.getSeconds() % 10)]:"");
break;
}
output +=unit[5];

 

return output;
}


/**//*
===========================================
//转换成农历
===========================================
*/
Date.prototype.toChinese = function()
{
//暂缺
}

/**//*
===========================================
//是否是闰年
===========================================
*/
Date.prototype.isLeapYear = function()
{
return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));
}

/**//*
===========================================
//获得该月的天数
===========================================
*/
Date.prototype.getDayCountInMonth = function()
{
var mon = new Array(12);

    mon[0] = 31; mon[1] = 28; mon[2] = 31; mon[3] = 30; mon[4]  = 31; mon[5]  = 30;
    mon[6] = 31; mon[7] = 31; mon[8] = 30; mon[9] = 31; mon[10] = 30; mon[11] = 31;

if(0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0))&&this.getMonth()==2)
{
return 29;
}
else
{
return mon[this.getMonth()];
}
}

/**//*
===========================================
//获得日期为星期几 (0为星期天)
===========================================
*/
Date.prototype.weekOfDay = function()
{
return this.getDay();
}

/**//*
===========================================
//日期比较
===========================================
*/
Date.prototype.Compare = function(objDate)
{
if(typeof(objDate)!="object" && objDate.constructor != Date)
{
return -2;
}

var d = this.getTime() - objDate.getTime();

if(d>0)
{
return 1;
}
else if(d==0)
{
return 0;
}
else
{
return -1;
}
}


/**//*
===========================================
//格式化日期格式
===========================================
*/
Date.prototype.toString = function()
{
if(arguments.length>0)
{
var formatStr = arguments[0];
var str = formatStr;

str=str.replace(/yyyy|YYYY/,this.getFullYear());
str=str.replace(/yy|YY/,(this.getFullYear() % 100)>9?(this.getFullYear() % 100).toString():"0" + (this.getFullYear() % 100));

str=str.replace(/MM/,this.getMonth()+1>9?(this.getMonth()+1).toString():"0" + (this.getMonth()+1));
str=str.replace(/M/g,(this.getMonth()+1).toString());

str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():"0" + this.getDate());
str=str.replace(/d|D/g,this.getDate());

str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():"0" + this.getHours());
str=str.replace(/h|H/g,this.getHours());

str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():"0" + this.getMinutes());
str=str.replace(/m/g,this.getMinutes());

str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():"0" + this.getSeconds());
str=str.replace(/s|S/g,this.getSeconds());

return str;

}
else
{
return this.toLocaleString();
}
}

/**//*
===========================================
//由字符串直接实例日期对象
===========================================
*/
Date.prototype.instanceFromString = function(str)
{
return new Date(str.replace(/-/g, "\/"));
}

/**//*
===========================================
//得到日期年月日等加数字后的日期
===========================================
*/
Date.prototype.dateAdd = function(interval,number)
{
var date = this;

    switch(interval)
    {
        case "y" :
            date.setFullYear(date.getFullYear()+number);
            return date;

        case "q" :
            date.setMonth(date.getMonth()+number*3);
            return date;

        case "m" :
            date.setMonth(date.getMonth()+number);
            return date;

        case "w" :
            date.setDate(date.getDate()+number*7);
            return date;
       
        case "d" :
            date.setDate(date.getDate()+number);
            return date;

        case "h" :
            date.setHours(date.getHours()+number);
            return date;

case "m" :
            date.setMinutes(date.getMinutes()+number);
            return date;

case "s" :
            date.setSeconds(date.getSeconds()+number);
            return date;

        default :
            date.setDate(d.getDate()+number);
            return date;
    }
}

/**//*
===========================================
//计算两日期相差的日期年月日等
===========================================
*/
Date.prototype.dateDiff = function(interval,o)
{
//判断o是否为日期对象
if(o&&o.constructor==Date)
{
//判断是否interval是否是字符串对象
if (interval&&interval.constructor==String)
{

var _start= this.getTime();
var _end= o.getTime();

var number= _end - _start;

var iOut = -1;

  
switch (interval.charAt(0))
{
case 'y':case 'Y'://year
iOut =  o.getFullYear() - this.getFullYear();
break;
case 'm':case 'M'://month
iOut = (o.getFullYear() - this.getFullYear()) * 12 + (o.getMonth()-this.getMonth());
break;
case 'q':case 'Q'://quarter
iOut = ((o.getFullYear() - this.getFullYear()) * 12 + (o.getMonth()-this.getMonth()))/3;
break;
case 'd':case 'D'://day
iOut = parseInt(number / 86400000) ;
break;
case 'w':case 'W'://week
iOut = parseInt(number / 86400000/7) ;
break;
case 'h':case 'H'://hour
iOut = parseInt(number / 3600000 ) ;
break;
case 'n':case 'N'://minute
iOut = parseInt(number / 60000 ) ;
break;
case 's': case 'S'://second
iOut = parseInt(number / 1000 ) ;
break;
case 't':case 'T'://microsecond
iOut = parseInt(number);
break;
default:
iOut = -1;
}

return iOut;
}
}

return -1

}


/**//*
===========================================
//得到日期的组成部分
===========================================
*/
Date.prototype.datePart = function(interval)
{

if(interval==null)
{
return -1;
}

if(/^(yy|yyyy)$/.test(interval))
{
return this.getFullYear();
}

if(/^(qq|q)$/.test(interval))
{
return Math.ceil((this.getMonth()+1) / 4);
}

if(/^(mm|m)$/.test(interval))
{
return this.getMonth();
}

if(/^(dd|d)$/.test(interval))
{
return this.getDate();
}

if(/^(dw)$/.test(interval))
{
return this.getDay();
}

if(/^(hh|h)$/.test(interval))
{
return this.getHours();
}

if(/^(mi|n)$/.test(interval))
{
return this.getMinutes();
}

if(/^(ss|s)$/.test(interval))
{
return this.getSeconds();
}

if(/^(ms)$/.test(interval))
{
return this.getMilliseconds();
}

//缺少日期的第几周,第几天

return -1;
}


**
*功能:返回格式化后的日期字符串
*参数:formatStr为格式字符串,其中表示形式如下列表
*“ddd”-汉字星期几
*“yyyy”-四位数年份
*“MM”-两位数月份
*“dd”-两位数日期
*“hh”-两位数小时
*“mm”-两位数分钟
*“ss”-两位数秒数
*“y”-年份
*“M”-月份
*“d”-日期
*“h”-小时
*“m”-分钟
*“s”-秒数
*/
Date.prototype.format = function (formatStr) {
var WEEK = new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六");
var s = formatStr;

s = s.replace(/d{3}/g, WEEK[this.getDay()]);

s = s.replace(/y{4}/g, this.getFullYear());
s = s.replace(/M{2}/g, (this.getMonth()+1)<10 ? "0"+(this.getMonth()+1) : (this.getMonth()+1));
s = s.replace(/d{2}/g, this.getDate()<10 ? "0"+this.getDate() : this.getDate());
s = s.replace(/h{2}/g, this.getHours()<10 ? "0"+this.getHours() : this.getHours());
s = s.replace(/m{2}/g, this.getMinutes()<10 ? "0"+this.getMinutes() : this.getMinutes());
s = s.replace(/s{2}/g, this.getSeconds()<10 ? "0"+this.getSeconds() : this.getSeconds());

s = s.replace(/y{1}/g, this.getFullYear());
s = s.replace(/M{1}/g, this.getMonth() + 1);
s = s.replace(/d{1}/g, this.getDate());
s = s.replace(/h{1}/g, this.getHours());
s = s.replace(/m{1}/g, this.getMinutes());
s = s.replace(/s{1}/g, this.getSeconds());

return(s);
}

 

 zhaoxiaoyang(梅雪香@深圳)
整理完毕,发出来大家测测,有意见和建议快提,我好快改

另:计算两个日期的差的功能,我不清楚该如何设计.请大家发表高论!



 

又改写了一下,可以用所有初始化Date对象的方法来初始化PowerDate对象了,而且可以是更不符合要求的字符串如: new PowerDate("  2005@#@#8----22    ");也一样可以成功初始化,只是一定要包含三个数值.
农历的算法太长了,而且在开发中也很少应用,所以暂不加到该类中来.
新代码如下:


新加了记算日期的方法,请大家帮测一下

/**//*功能:返回两日期之差
 *参数:pd   PowerDate对象
 *    type: 返回类别标识.yy:年,mm:月,dd:日,hh:小时,mi:分,ss:秒,ms:毫秒
 *    intOrFloat :返回整型还是浮点型值 0:整型,1:浮点型
 */
this.calDateDistance = function (pd,type,intOrFloat){
var miSecMain = this.date.valueOf();
var miSecSub  = pd.getDate().valueOf();
var num=0;
switch(type){
case "yy": num = this.getFullYear() - pd.getFullYear();
break;
case "mm": num = (this.getFullYear() - pd.getFullYear())*12+this.getMonth()-pd.getMonth();
break;
case "dd": num = this.fmtRtnVal((miSecMain-miSecSub)/86400000,intOrFloat);
break;
case "hh": num = this.fmtRtnVal((miSecMain-miSecSub)/3600000,intOrFloat);
break;
case "mi": num = this.fmtRtnVal((miSecMain-miSecSub)/60000,intOrFloat);
break;
case "ss": num = this.fmtRtnVal((miSecMain-miSecSub)/1000,intOrFloat);
break;
case "ms": num = (miSecMain-miSecSub);
break;
default:
throw new Error(-1,"没有您要求返回的类型,请检查输入参数!");
break;
}
return num;
};
this.fmtRtnVal = function (val,intOrFloat){
//alert(val);
return (intOrFloat == 0 ? Math.floor(val) : parseInt(val*100)/100);
};

 

测试语句:

var d= new PowerDate(new Date());//实例化一个PowerDate对象
alert(d.calDateDistance(new  PowerDate("2005/5/31"),"hh",1));//输出日期字符串

本文作者:佚名 来源:http://www.cnblogs.com/goody9807/
CIO之家 www.ciozj.com 微信公众号:imciow
   
免责声明:本站转载此文章旨在分享信息,不代表对其内容的完全认同。文章来源已尽可能注明,若涉及版权问题,请及时与我们联系,我们将积极配合处理。同时,我们无法对文章内容的真实性、准确性及完整性进行完全保证,对于因文章内容而产生的任何后果,本账号不承担法律责任。转载仅出于传播目的,读者应自行对内容进行核实与判断。请谨慎参考文章信息,一切责任由读者自行承担。
延伸阅读