javascript日期操作

时间对象是一个我们经常要用到的对象,无论是做时间输出、时间判断等操作时都与这个对象离不开。它是一个内置对象。

IE8不支持new Date(“2016-3-28”)这种格式的日期声明方式,如果使用会提示NaN。可以使用new Date(year, month, day)这种方式代替。注意其中month范围是0~11。

在网上找到一段代码,用来格式化时间的。
An Extended ISO 8601 local Date format YYYY-MM-DD can be parsed to a Date with the following:

function parseISO8601(dateStringInRange) {
  var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
  date = new Date(NaN),
  month,
  parts = isoExp.exec(dateStringInRange);
  if(parts) {
    month = +parts[2];
    date.setFullYear(parts[1], month - 1, parts[3]);
    if(month != date.getMonth() + 1) {
    date.setTime(NaN);
  }
}
return date;
}

方法:分为得到时间方法、设置时间方法和转换时间方法 得到时间方法

几个需要注意的地方:

1、得到日期和年和设置日期和年时间,其中很怪的问题就是不能对月份进行设置(比较的怪):

<script language="javascript">
d = new Date();
alert(d.toLocaleString());
d.setDate(25);
alert(d.toLocaleString());
d.setYear(2000);
alert(d.toLocaleString());
</script>

2、获得年的时候最好用getFullYear()方法来做
3、由于针对月份,JS是从0开始的,因此需要对月份进行操作时要加1

下面是几个关于时间的经典而且经常会用到的例子,希望对大家会有提高的。

1、将2005-8-5转换成2005-08-05格式
<script language="javascript">
var strDate = '2005-8-5';
window.alert(strDate.replace(/\b(\w)\b/g, '0$1'));
</script>
2、得到间隔天数
<script type="text/javascript">
<!--
alert("间隔天数为:"+(new Date('2005/8/15')-new Date('2003/9/18'))/1000/60/60/24+"天")
-->
</script>
3、得到间隔时间
<script>
var d1=new Date("2004/09/16 20:08:00");
var d2=new Date("2004/09/16 10:18:03");
var d3=d1-d2;
var h=Math.floor(d3/3600000);
var m=Math.floor((d3-h*3600000)/60000);
var s=(d3-h*3600000-m*60000)/1000;
alert("相差"+h+"小时"+m+"分"+s+"秒");
</script>
4、得到今天的日期
<script language="javascript">
d = new Date();
alert(d.getFullYear()+"年"+(d.getMonth()+1)+"月"+d.getDate()+"日");
</script>
6、数字日期转汉字
<html>
<head>
<title> New Document </title>
</head>
<body>
<script language=javascript>
Date.prototype.getRead = function() {
var values = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九");
var returnValue, temp;
returnValue = this.getYear()+"年";
temp = (this.getMonth()+1)+"月"+this.getDate()+"日";
temp = temp.replace(/(\d)(\d)/g,"$1十$2").replace(/1十/g,"十").replace(/十0/g,"十");
returnValue += temp;
returnValue = returnValue.replace(/\d/g, function(sts){
return values[parseInt(sts)]
});
return returnValue;
}
var t=new Date();
document.write(t.getRead());
</script>
</body>
</html>
7、得到前N天或后N天的日期

方法一:

<script type="text/javascript">
function showdate(n) {
var uom = new Date(new Date()-0+n*86400000);
uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate();
return uom;
}
window.alert("今天是:"+showdate(0));
window.alert("昨天是:"+showdate(-1));
window.alert("明天是:"+showdate(1));
window.alert("10天前是:"+showdate(-10));
window.alert("5天后是:"+showdate(5));
</script>

方法二:

<script type="text/javascript">
function showdate(n) {
var uom = new Date();
uom.setDate(uom.getDate()+n);
uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate();
return uom;
}
window.alert("今天是:"+showdate(0));
window.alert("昨天是:"+showdate(-1));
window.alert("明天是:"+showdate(1));
window.alert("10天前是:"+showdate(-10));
window.alert("5天后是:"+showdate(5));
</script>

方法三:

<script language="Javascript">
Date.prototype.getDays=function(){
var _newDate=new Date();
_newDate.setMonth(_newDate.getMonth()+1);
_newDate.setDate(0);
$_days=_newDate.getDate();
delete _newDate;
return $_days;
}
function showdate(n) {
var uom = new Date();
uom.setDate(uom.getDate()+n);
uom = uom.getFullYear() + "-" + (uom.getMonth()+1) + "-" + uom.getDate()+"\n星期"+('天一二三四五六'.charAt(uom.getDay()))+"\n本月有"+ uom.getDays()+"天";
return uom;
}
window.alert("今天是:"+showdate(0));
window.alert("昨天是:"+showdate(-1));
window.alert("明天是:"+showdate(1));
window.alert("10天前是:"+showdate(-10));
window.alert("5天后是:"+showdate(5));
</script>
javascript对日期处理的常用方法类
<script language="JavaScript">
<!--

//程序:常用公历日期处理程序

/*
*  用相对不规则的字符串来创建日期对象,
*  不规则的含义为:顺序包含年月日三个数值串,有间隔
*/
String.prototype.parseDate=function(){
  var ar=(this+",0,0,0").match(/d+/g);
  return ar[5] ? (new Date(ar[0],ar[1]-1,ar[2],ar[3],ar[4],ar[5])) : (new Date());
}

/*
*  功能:根据输入表达式返回日期字符串
*  参数:dateFmt:字符串,由以下结构组成
*  yy:长写年,YY:短写年mm:数字月,MM:英文月,dd:日,hh:时,
*  mi:分,ss秒,ms:毫秒,we:汉字星期,WE:英文星期.
*  isFmtWithZero:是否用0进行格式化,true or false
*  返回:对应日期的中文字符串
*/
Date.prototype.toString=function(dateFmt, isFmtWithZero){
  dateFmt=(dateFmt==null ? "yy-mm-dd hh:mi:ss" : dateFmt);
  if(typeof(dateFmt)!="string")
  throw(newError(-1,'toString()方法的第一个参数为字符串类型!'));
  isFmtWithZero=!!isFmtWithZero;
  var weekArr=[["日","一","二","三","四","五","六"], ["SUN","MON","TUR","WED","THU","FRI","SAT"]];
  var monthArr=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];    var str=dateFmt;
  var o={
    "yy":this.getFullYear(),
    "YY":this.getYear(),
    "mm":this.getMonth()+1,
    "MM":monthArr[this.getMonth()],
    "dd":this.getDate(),
    "hh":this.getHours(),
    "mi":this.getMinutes(),
    "ss":this.getSeconds(),
    "we":"星期"+weekArr[0][this.getDay()],
    "WE":weekArr[1][this.getDay()]
  }
  for(var i in o){
    str=str.replace(newRegExp(i,"g"),o[i].toString().fmtWithZero(isFmtWithZero));
  }
  str=str.replace(/ms/g,this.getMilliseconds().toString().fmtWithZeroD(isFmtWithZero));
  return str;
}

/*
*  将一位数字格式化成两位,如:9 to 09
*/
String.prototype.fmtWithZero=function(isFmtWithZero){
  //正则表达式中^表示开始,$表示结束,d表示数字
  return (isFmtWithZero && /^d$/.test(this)) ? "0"+this : this;
}
String.prototype.fmtWithZeroD=function(isFmtWithZero){
  //此处应为补齐三位
  return (isFmtWithZero && /^d{2}$/.test(this)) ? "0"+this : ( (isFmtWithZero && /^d$/.test(this)) ? "00"+this : this);
}

/*功能:返回与某日期相距N天(N个24小时)的日期*参数:numnumber类型可以为正负整数或者浮点数,默认为1;
*  type0(秒)or1(天),默认为天
*  返回:新的Date对象
*/
Date.prototype.dateAfter=function(num,type){
num=(num==null?1:num);
if(typeof(num)!="number")
throw new Error(-1,"dateAfterDays(num,type)的num参数为数值类型.");
type=(type==null?1:type);
var arr=[1000,86400000];
returnnewDate(this.valueOf()+num*arr[type]);}

//判断是否是闰年,返回true或者false
Date.prototype.isLeapYear=function(){
var year=this.getFullYear();
return(0==year%4&&((year%100!=0)||(year%400==0)));
}

//返回该月天数Date.prototype.getDaysOfMonth=function(){
return(newDate(this.getFullYear(),this.getMonth()+1,0)).getDate();
}

//日期比较函数,参数date:为Date类型,如this日期晚于参数:1,相等:0早于:-1
Date.prototype.dateCompare=function(date){
  if(typeof(date)!="object"||!(/Date/.test(date.constructor)))
    thrownewError(-1,"dateCompare(date)的date参数为Date类型.");
  var d=this.getTime()-date.getTime();
  return d>0?1:(d==0?0:-1);
}

/*功能:返回两日期之差*参数:pd PowerDate对象
*  type:返回类别标识.yy:年,mm:月,ww:周,dd:日,hh:小时,mi:分,ss:秒,ms:毫秒*  intOrFloat:返回整型还是浮点型值0:整型,不等于0:浮点型
*  output:输出提示,如:时间差为#周!
*/
Date.prototype.calDateDistance=function(date,type,intOrFloat,output){
  if( typeof(date) != "object" || !(/Date/.test(date.constructor)))
    thrownewError(-1,"calDateDistance(date,type,intOrFloat)的date参数为Date类型.");
  type=(type==null?'dd':type);
  if(!((newRegExp(type+",","g")).test("yy,mm,ww,dd,hh,mi,ss,ms,")))
    thrownewError(-1,"calDateDistance(pd,type,intOrFloat,output)的type参数为非法.");
  variof=(intOrFloat==null?0:intOrFloat);
  varnum=0;
  varo={
    "ww":7*86400000,
    "dd":86400000,
    "hh":3600000,
    "mi":60000,
    "ss":1000,
    "ms":1
  }
  switch(type){
    case"yy":num=this.getFullYear()-date.getFullYear();break;
    case"mm":num=(this.getFullYear()-date.getFullYear())*12+this.getMonth()-date.getMonth();break;
    default:      varsub=this.valueOf()-date.valueOf();      if(o[type])        num=(sub/o[type]).fmtRtnVal(iof);      break;
  }
  return(output?output.replace(/#/g,""+num+""):num);
}

//返回整数或者两位小数的浮点数Number.prototype.fmtRtnVal=function(intOrFloat)
{
return(intOrFloat==0?Math.floor(this):parseInt(this*100)/100);
}

//根据当前日期所在年和周数返回周日的日期Date.prototype.RtnByWeekNum=function(weekNum){
if(typeof(weekNum)!="number")    thrownewError(-1,"RtnByWeekNum(weekNum)的参数是数字类型.");  vardate=newDate(this.getFullYear(),0,1);
varweek=date.getDay();
week=(week==0?7:week);
returndate.dateAfter(weekNum*7-week,1);}

//根据日期返回该日期所在年的周数
Date.prototype.getWeekNum=function(){
vardat=newDate(this.getFullYear(),0,1);
varweek=dat.getDay();
week=(week==0?7:week);
vardays=this.calDateDistance(dat,"dd")+1;
return((days+6-this.getDay()-7+week)/7);}
//-->
</script>
<script language="JavaScript">
<!--
var dw=document.write;
var date2="2005-12-30".parseDate();
dw(date2,"
"
); vardate3="2006-1-10111111".parseDate(); dw(date2.calDateDistance(date3,null,null,"时间差为#天!")); //alert(newDate(2000,2,-29)); // --> </script>
字符串转日期
function toDate(str){
    var sd=str.split("-");
    return new Date(sd[0],sd[1],sd[2]);
}
//在IE8以下是不支持的
function toDate(str){
    return new Date(str);
}
比较日期大小
var d1=toDate("2001-2-2 ");
var d2=toDate("2001-2-3");
alert(d1>d2);
获取两日期月份之差
var diff = (date1. getFullYear() - date2.getFullYear()) * 12
               + date1.getMonth() - date2.getMonth();

作者:JasonQiao
链接:https://www.jianshu.com/p/faf30879fbce
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

你可能感兴趣的:(javascript日期操作)