zoukankan      html  css  js  c++  java
  • Javascript对日期的操作,日期函数

    =====================

    javascript日期操作

    时间对象是一个我们经常要用到的对象,无论是做时间输出、时间判断等操作时都与这个对象离不开。除开JavaScript中的时间对象外,在VbScript中也有许多的时间对象,而且非常好用。下面还是按照我们的流程来进行讲解。
    它是一个内置对象——而不是其它对象的属性,允许用户执行各种使用日期和时间的过程。
     方法:分为得到时间方法、设置时间方法和转换时间方法
    得到时间方法:
      getDate() 查看Date对象并返回日期
      getDay() 返回星期几
      getHours() 返回小时数
      getMinutes() 返回分钟数
      getMonth() 返回月份值
      getSeconds() 返回秒数
      getTime() 返回完整的时间
      getYear() 返回年份
    设置时间方法:
      setDate() 改变Date对象的日期
      setHours() 改变小时数
      setMinutes() 改变分钟数
      setMonth() 改变月份
      setSeconds() 改变秒数
      setTime() 改变完整的时间
      setYear() 改变年份
    转换时间方法:
      toGMTString() 把Date对象的日期(一个数值)转变成一个GMT时间字符串,返回类似下面的值:Weds,15 June l997 14:02:02 GMT(精确的格式依赖于计算机上所运行的操作系统而变)
      toLocaleString() 把Date对象的日期(一个数值)转变成一个字符串,使用所在计算机上配置使用的特定日期格式
      UTC() 使用Date UTC(年、月、日、时、分、秒),以自从1970年1月1日00:00:00(其中时、分、秒是可选的)以来的毫秒数的形式返回日期
    几个需要注意的地方:
    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>
    方法三(不好意思,这个市用vsscript做的):
    <script language="vbscript">
    function showdate(n)
    showdate=dateadd("d",date(),n)
    end function
    msgbox "今天是:"&showdate(0)
    msgbox "昨天是:"&showdate(-1)
    msgbox "明天是:"&showdate(1)
    msgbox "十天前是:"&showdate(-10)
    msgbox "五天后是:"&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>

    From: http://www.blogjava.net/parable-myth/archive/2008/01/12/174761.html

    =====================

    javascript 日期函数

     

    From: http://www.3800hk.com/Article/web/JavaScript/yyjqjs/2005-08-06/Article_47290.html

    =====================

    javascript对日期处理的常用方法类

    <scriptlanguage="JavaScript">
    <!--
    //程序:常用公历日期处理程序
    /**//*用相对不规则的字符串来创建日期对象,不规则的含义为:顺序包含年月日三个数值串,有间隔*/
    String.prototype.parseDate=function(){
      varar=(this+",0,0,0").match(/d+/g);
      returnar[5]?(newDate(ar[0],ar[1]-1,ar[2],ar[3],ar[4],ar[5])):(newDate());
    }
    /**//*
    *功能:根据输入表达式返回日期字符串
    *参数:dateFmt:字符串,由以下结构组成  
    *   yy:长写年,YY:短写年mm:数字月,MM:英文月,dd:日,hh:时,
    *   mi:分,ss秒,ms:毫秒,we:汉字星期,WE:英文星期.
    *   isFmtWithZero:是否用0进行格式化,trueorfalse
    *返回:对应日期的中文字符串
    */
    Date.prototype.toString=function(dateFmt,isFmtWithZero){
      dateFmt=(dateFmt==null?"yy-mm-ddhh:mi:ss":dateFmt);
      if(typeof(dateFmt)!="string")
        throw(newError(-1,'toString()方法的第一个参数为字符串类型!'));
      isFmtWithZero=!!isFmtWithZero;
      varweekArr=[["日","一","二","三","四","五","六"],["SUN","MON","TUR","WED","THU","FRI","SAT"]];
      varmonthArr=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
      varstr=dateFmt;
      varo={
        "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(variino){
        str=str.replace(newRegExp(i,"g"),o[i].toString().fmtWithZero(isFmtWithZero));
      }
      str=str.replace(/ms/g,this.getMilliseconds().toString().fmtWithZeroD(isFmtWithZero));
      returnstr;
    }
    /**//*将一位数字格式化成两位,如:9to09*/
    String.prototype.fmtWithZero=function(isFmtWithZero){  
      return(isFmtWithZero&&/^d$/.test(this))?"0"+this:this;
    }
    String.prototype.fmtWithZeroD=function(isFmtWithZero){  
      return(isFmtWithZero&&/^d{2}$/.test(this))?"00"+this:((isFmtWithZero&&/^d$/.test(this))?"0"+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")thrownewError(-1,"dateAfterDays(num,type)的num参数为数值类型.");
      type=(type==null?1:type);
      vararr=[1000,86400000];
      returnnewDate(this.valueOf()+num*arr[type]);
    }
    //判断是否是闰年,返回true或者false
    Date.prototype.isLeapYear=function(){
      varyear=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类型.");
      vard=this.getTime()-date.getTime();
      returnd>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>
    <scriptlanguage="JavaScript">
    <!--
    vardw=document.write;
    vardate2="2005-12-30".parseDate();
    dw(date2,"<br>");
    vardate3="2006-1-10111111".parseDate();
    dw(date2.calDateDistance(date3,null,null,"时间差为#天!"));
    //alert(newDate(2000,2,-29));
    //-->
    </script>

    From: http://edu.cnzz.cn/NewsInfo/22310.aspx

  • 相关阅读:
    Oracle最大连续访问天数
    oracle中MINUS
    sql中含有中文,export oralce编码格式的环境变量
    alternate_file_dcol_rollback
    oracle查询分区表
    hive创建表sql
    使用ANSI改变终端输出样式
    Golang中的空字符,似花不是花
    程序员必看 Linux 常用命令(重要)
    MongoDB入门介绍与案例分析
  • 原文地址:https://www.cnblogs.com/emanlee/p/1429666.html
Copyright © 2011-2022 走看看