zoukankan      html  css  js  c++  java
  • JavaScript(8):Date日期函数

    默认情况下,JavaScript 将使用浏览器的时区并将日期显示为全文本字符串:

    Tue Apr 02 2019 09:01:19 GMT+0800 (中国标准时间)

    稍后,您将在本教程学到更多关于如何显示日期的知识。

    一、创建 Date 对象

    Date 对象由新的 Date() 构造函数创建。

    有 4 种方法创建新的日期对象。

    1、new Date():前日期和时间创建新的日期对象

    new Date() 用当:日期对象是静态的。计算机时间正在滴答作响,但日期对象不会。

    var d = new Date();

    2、new Date(year, month, ...):用指定日期和时间创建新的日期对象。

    注释:JavaScript 从 0 到 11 计算月份。一月是 0。十二月是11。

    var d = new Date(2018, 11, 24, 10, 33, 30, 0); //七个数字分别指定年、月、日、小时、分钟、秒和毫秒(按此顺序):
    var d = new Date(2018, 11, 24, 10, 33, 30); //六个数字指定年、月、日、小时、分钟、秒
    var d = new Date(2018, 11, 24, 10, 33); //五个数字指定年、月、日、小时和分钟
    var d = new Date(2018, 11, 24, 10); //四个数字指定年、月、日和小时
    var d = new Date(2018, 11, 24); //三个数字指定年、月和日
    var d = new Date(2018, 11); //两个数字指定年份和月

    注意:您不能省略月份。如果只提供一个参数,则将其视为毫秒。

    var d = new Date(2018);

    一位和两位数年份将被解释为 19xx 年:

    var d = new Date(99, 11, 24);
    var d = new Date(9, 11, 24);

    3、new Date(dateString):从日期字符串创建一个新的日期对象

    有四种 JavaScript 日期输入格式

    1、ISO 日期(年、月、日)

    ISO 8601 是表现日期和时间的国际标准。ISO 8601 语法 (YYYY-MM-DD) 也是首选的 JavaScript 日期格式,计算的日期相对于您的时区。

    var d = new Date("2018-02-19"); //根据您的时区,上面的结果将在 2 月 18 日至 2 月 19 日之间变化。
    var d = new Date("2015-03"); //ISO 日期(年和月) 时区会对结果在 2 月 28 日至 3 月 1 日之间产生变化。
    var d = new Date("2018"); //ISO 日期(只有年) 时区会对结果在 2017 年 12 月 31 日至 2018 年 1 月 1 日之间产生变化。
    var d = new Date("2018-02-19T12:00:00"); //ISO 日期(完整的日期加时、分和秒(YYYY-MM-DDTHH:MM:SS):)日期和时间通过大写字母 T 来分隔。

    UTC(Universal Time Coordinated)协调世界时,又称世界统一时间,世界标准时间,国际协调时间。UTC 时间通过大写字母 Z 来定义。等同于 GMT(格林威治时间)

    var d = new Date("2018-02-19T12:00:00-08:30"); //如果您希望修改相对于 UTC 的时间,请删除 Z 并用 +HH:MM 或 -HH:MM 代替:

    在日期-时间字符串中省略 T 或 Z,在不同浏览器中会产生不同结果。

    时区

    在设置日期时,如果不规定时区,则 JavaScript 会使用浏览器的时区。当获取日期时,如果不规定时区,则结果会被转换为浏览器时区。

    换句话说,如果用户从中国进行浏览,假如日期/时间以 GMT(格林威治标准时间)创建,该日期/时间将被转换为 CST(中国标准时间)

    2、JavaScript 短日期

    var d = new Date("02/19/2018"); //短日期通常使用 "MM/DD/YYYY" 这样的语法:

    在某些浏览器中,不带前导零的月或其会产生错误:

    var d = new Date("2018-2-19");

    3、JavaScript 长日期

    var d = new Date("Feb 19 2018"); //长日期通常以 "MMM DD YYYY" 这样的语法来写:
    var d = new Date("19 Feb 2018"); //月和天能够以任意顺序出现:
    var d = new Date("February 19 2018"); //月能够以全称 (January) 或缩写 (Jan) 来写:
    var d = new Date("FEBRUARY, 25, 2015"); //逗号会被忽略,且对大小写不敏感:

    4、JavaScript 完整日期

    var d = new Date("Mon Feb 19 2018 06:55:23 GMT+0100 (W. Europe Standard Time)"); /avaScript 接受“完整 JavaScript 格式”的日期字符串:

    JavaScript 会忽略日期名称和时间括号中的错误:

    var d = new Date("Fri Mar 26 2018 09:56:24 GMT+0100 (Tokyo Time)");

    4、new Date(milliseconds):创建一个零时加毫秒的新日期对象:

    JavaScript 将零时间存储为自 1970 年 1 月 1 日 00:00:00 UTC(协调世界时)以来的毫秒数。

    现在的时间是:1970 年 1 月 1 日之后的 1554166879383 毫秒。

    var d = new Date(100000000000);//1970年 1 月 1 日加上100 000 000 000毫秒,大约是 1973 年 3 月 3 日:
    var d = new Date(-100000000000);//1970 年 1 月 1 日减去 100 000 000 000 毫秒大约是 1966 年 10 月 31 日:
    var d = new Date(86400000);//一天(24 小时)是 86 400 000 毫秒。

    二、显示日期

    JavaScript(默认情况下)将以全文本字符串格式输出日期:

    Wed Mar 25 2015 08:00:00 GMT+0800 (中国标准时间)

    • 1、toString() :日期对象自动转换为字符串.在 HTML 中显示日期对象时,会使用 toString() 方法自动转换为字符串。
    • 2、toUTCString() :将日期转换为 UTC 字符串(一种日期显示标准)。
    • 3、toDateString() :将Date 对象的日期部分转换为字符串。
    • 4、toTimeString():把 Date 对象的时间部分转换为字符串。
    • 5、toLocaleString():根据本地时间格式,把 Date 对象转换为字符串。
    • 6、toLocaleDateString():根据本地时间格式,把 Date 对象的日期部分转换为字符串。
    • 7、toLocaleTimeString():根据本地时间格式,把 Date 对象的时间部分转换为字符串。
    var d = new Date();
    document.write(d);//Wed Mar 04 2020 14:36:11 GMT+0800 (中国标准时间)
    document.write(d.toString());//Wed Mar 04 2020 14:36:24 GMT+0800 (中国标准时间)
    document.write(d.toUTCString());// Wed, 04 Mar 2020 06:32:15 GMTWed Mar 04 2020 14:32:15 GMT+0800 (中国标准时间)
    document.write(d.toDateString());// Wed, 04 Mar 2020 06:36:50 GMTWed Mar 04 2020
    document.write(d.toTimeString());// 14:37:04 GMT+0800 (中国标准时间)
    document.write(d.toLocaleString());// 2020/3/4 下午2:37:13
    document.write(d.toLocaleDateString());//2020/3/4
    document.write(d.toLocaleTimeString());// 下午2:37:33

    三、日期获取方法

    日期方法允许您获取并设置日期值(年、月、日、时、分、秒、毫秒)

    1. getFullYear() 方法:获取四位的年(yyyy)
    2. getMonth() 方法:获取月(0-11)
    3. getDate() 方法:以数值返回天(1-31)
    4. getHours() 方法:获取小时(0-23)
    5. getMinutes() 方法:获取分(0-59)
    6. getSeconds() 方法:获取秒(0-59)
    7. getMilliseconds() 方法:获取毫秒(0-999)
    8. getDay() 方法:以数值获取星期名(0-6)
    9. getTime() 方法:获取时间(从 1970 年 1 月 1 日至今)
    var d = new Date();
    document.getElementById("demo").innerHTML = d.getFullYear() //getFullYear() 方法以四位数字形式返回日期年份:
    document.getElementById("demo").innerHTML = d.getMonth(); //getMonth() 以数字(0-11)返回日期的月份:在 JavaScript 中,第一个月(1 月)是月号 0,因此 12 月返回月号 11。
    document.getElementById("demo").innerHTML = d.getDate(); //getDate() 方法以数字(1-31)返回日期的日:
    document.getElementById("demo").innerHTML = d.getHours(); //getHours() 方法以数字(0-23)返回日期的小时数:
    document.getElementById("demo").innerHTML = d.getMinutes(); //getMinutes() 方法以数字(0-59)返回日期的分钟数:
    document.getElementById("demo").innerHTML = d.getSeconds(); //getSeconds() 方法以数字(0-59)返回日期的秒数:
    document.getElementById("demo").innerHTML = d.getMilliseconds(); //getMilliseconds() 方法以数字(0-999)返回日期的毫秒数:
    document.getElementById("demo").innerHTML = d.getDay(); //getDay() 方法以数字(0-6)返回日期的星期名(weekday):在 JavaScript 中,一周的第一天(0)表示“星期日”
    document.getElementById("demo").innerHTML = d.getTime(); //getTime() 方法返回自 1970 年 1 月 1 日以来的毫秒数:

    您可以使用名称数组,并使用 getMonth() 将月份作为名称返回:

    var d = new Date();
    var months = 
                [
                "January", "February", "March", "April", "May", "June", 
                "July", "August", "September", "October", "November", "December"
                ];
    document.getElementById("demo").innerHTML = months[d.getMonth()];

    您可以使用名称数组,并使用 getDay() 将星期名作为名称返回:

    var d = new Date();
    var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    document.getElementById("demo").innerHTML = days[d.getDay()];

    四 、日期设置方法

    使用“设置日期”方法可以设置日期对象的日期值(年、月、日、小时、分钟、秒、毫秒)。

    设置方法用于设置日期的某个部分。下面是最常用的方法(按照字母顺序排序):

    1. setFullYear() 方法:设置年(可选月和日)
    2. setMonth() 方法:设置月(0-11)
    3. setDate() 方法:以数值(1-31)设置日
    4. setHours() 方法:设置小时(0-23)
    5. setMinutes() 方法:设置分(0-59)
    6. setSeconds() 方法:设置秒(0-59)
    7. setMilliseconds():设置毫秒(0-999)
    8. setTime():设置时间(从 1970 年 1 月 1 日至今的毫秒数)
    var d = new Date();
    d.setFullYear(2020);        //setFullYear() 方法设置日期对象的年份。这个例子设置为 2020 年:
    d.setFullYear(2020, 11, 3);;//setFullYear() 方法可以选择设置月和日d.setMonth(11);//setMonth() 方法设置日期对象的月份(0-11)
    d.setDate(15);              //setDate() 方法设置日期对象的日(1-31)
    d.setDate(d.getDate() + 50);//setDate() 方法也可用于将天数添加到日期:如果添加天数,切换月份或年份,则更改将由 Date 对象自动处理。 
    d.setHours(22);             //setHours() 方法设置日期对象的小时(0-23)
    d.setMinutes(30);           //setMinutes() 方法设置日期对象的分钟(0-59)
    d.setSeconds(30);           //setSeconds() 方法设置日期对象的秒数(0-59
    document.getElementById("demo").innerHTML = d;

    五、常用日期类函数

    1、dateAdd 方法:返回已添加指定时间间隔的日期对象。

    dateObj.dateAdd(interval, number)

    /* 得到日期年月日等加数字后的日期 */ 
    Date.prototype.dateAdd = function(interval,number) 
    { 
        var d = this; 
        var k={'y':'FullYear', 'q':'Month', 'm':'Month', 'w':'Date', 'd':'Date', 'h':'Hours', 'n':'Minutes', 's':'Seconds', 'ms':'MilliSeconds'}; 
        var n={'q':3, 'w':7}; 
        eval('d.set'+k[interval]+'(d.get'+k[interval]+'()+'+((n[interval]||1)*number)+')'); 
        return d; 
    }

    2、dateDiff 方法:返回两个日期对象之间的时间间隔。

    dateObj.dateDiff(interval, dateObj2)

    interval 参数可以有以下值:

    • y:年
    • q:季度
    • m:月
    • d:日
    • w:周
    • h:小时
    • n:分钟
    • s:秒
    • ms:毫秒
    /* 计算两日期相差的日期年月日等 */ 
    Date.prototype.dateDiff = function(interval,objDate2) 
    { 
        var d=this, i={}, t=d.getTime(), t2=objDate2.getTime(); 
        i['y']=objDate2.getFullYear()-d.getFullYear(); 
        i['q']=i['y']*4+Math.floor(objDate2.getMonth()/4)-Math.floor(d.getMonth()/4); 
        i['m']=i['y']*12+objDate2.getMonth()-d.getMonth(); 
        i['ms']=objDate2.getTime()-d.getTime(); 
        i['w']=Math.floor((t2+345600000)/(604800000))-Math.floor((t+345600000)/(604800000)); 
        i['d']=Math.floor(t2/86400000)-Math.floor(t/86400000); 
        i['h']=Math.floor(t2/3600000)-Math.floor(t/3600000); 
        i['n']=Math.floor(t2/60000)-Math.floor(t/60000); 
        i['s']=Math.floor(t2/1000)-Math.floor(t/1000); 
        return i[interval]; 
    }

    3、DatePart方法:取得日期数据信息

    //+---------------------------------------------------  
    //| //| 参数 interval 表示数据类型  
    //| y 年 m月 d日 w星期 ww周 h时 n分 s秒  
    //+---------------------------------------------------  
    Date.prototype.DatePart = function(interval)  
     {   
         var myDate = this;  
         var partStr='';  
         var Week = ['日','一','二','三','四','五','六'];  
         switch (interval)  
         {   
             case 'y' :partStr = myDate.getFullYear();break;  
             case 'm' :partStr = myDate.getMonth()+1;break;  
             case 'd' :partStr = myDate.getDate();break;  
             case 'w' :partStr = Week[myDate.getDay()];break;  
             case 'ww' :partStr = myDate.WeekNumOfYear();break;  
             case 'h' :partStr = myDate.getHours();break;  
             case 'n' :partStr = myDate.getMinutes();break;  
             case 's' :partStr = myDate.getSeconds();break;  
         }  
         return partStr;  
     
    }

    4、Format方法:日期格式化

    //---------------------------------------------------  
    // 日期格式化(方法一) 
    // 格式 YYYY/yyyy/YY/yy 表示年份  
    // MM/M 月份  
    // W/w 星期  
    // dd/DD/d/D 日期  
    // hh/HH/h/H 时间  
    // mm/m 分钟  
    // ss/SS/s/S 秒  
    //---------------------------------------------------  
     Date.prototype.Format = function(formatStr)   
     {   
        var str = formatStr;   
         var Week = ['日','一','二','三','四','五','六'];  
     
        str=str.replace(/yyyy|YYYY/,this.getFullYear());   
        str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));   
      
        str=str.replace(/MM/,this.getMonth()>9?this.getMonth().toString():'0' + this.getMonth());   
        str=str.replace(/M/g,this.getMonth());   
     
        str=str.replace(/w|W/g,Week[this.getDay()]);   
        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;   
    }  
    
    // 日期格式化(方法二) 
    //var da = new Date().format('yyyy-MM-dd hh:mm:ss'); //将日期格式串,转换成先要的格式
    //alert("格式化日期类型 
    " + new Date() + "
     为字符串:" + da);
    Date.prototype.format = function (format) {
        var date = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S+": this.getMilliseconds()
        };
        if (/(y+)/i.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (var k in date) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1
                                ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
            }
        }
        return format;
    }

    六、JS 自定义函数

    //今天
    function showToDay() {
        var Nowdate = new Date();
        M = Number(Nowdate.getMonth()) + 1
        return Nowdate.getYear() + "-" + M + "-" + Nowdate.getDate();
    }
    
    //本周第一天
    function showWeekFirstDay() {
            var Nowdate = new Date();
            var WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000);
            return WeekFirstDay;
        }

    //本周最后一天
    function showWeekLastDay() {
        var Nowdate = new Date();
        var WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000);
        var WeekLastDay = new Date((WeekFirstDay / 1000 + 6 * 86400) * 1000);
        return WeekLastDay;
    }
    
    //本月第一天
    function showMonthFirstDay() {
            var Nowdate = new Date();
            var MonthFirstDay = new Date(Nowdate.getYear(), Nowdate.getMonth(), 1);
            return MonthFirstDay;
        }

    //本月最后一天
    function showMonthLastDay() {
            var Nowdate = new Date();
            var MonthNextFirstDay = new Date(Nowdate.getYear(), Nowdate.getMonth() + 1, 1);
            var MonthLastDay = new Date(MonthNextFirstDay - 86400000);
            return MonthLastDay;
        }

    //上月第一天
    function showPreviousFirstDay() {
            var MonthFirstDay = showMonthFirstDay()
            return new Date(MonthFirstDay.getYear(), MonthFirstDay.getMonth() - 1, 1)
        }
    
    //上月最后一天
    function showPreviousLastDay() {
            var MonthFirstDay = showMonthFirstDay();
            return new Date(MonthFirstDay - 86400000);
        }

    //上周第一天
    function showPreviousFirstWeekDay() {
            var WeekFirstDay = showWeekFirstDay()
            return new Date(WeekFirstDay - 86400000 * 7)
        }

    //上周最后一天
    function showPreviousLastWeekDay() {
            var WeekFirstDay = showWeekFirstDay()
            return new Date(WeekFirstDay - 86400000)
        }

    //上一天
    function showPreviousDay() {
            var MonthFirstDay = new Date();
            return new Date(MonthFirstDay - 86400000);
        }

    //下一天
    function showNextDay() {
            var MonthFirstDay = new Date();
            return new Date((MonthFirstDay / 1000 + 86400) * 1000);
        }
    
    //下周第一天
    function showNextFirstWeekDay() {
            var MonthFirstDay = showWeekLastDay()
            return new Date((MonthFirstDay / 1000 + 86400) * 1000)
        }

    //下周最后一天
    function showNextLastWeekDay() {
            var MonthFirstDay = showWeekLastDay()
            return new Date((MonthFirstDay / 1000 + 7 * 86400) * 1000)
        }
    
    //下月第一天
    function showNextFirstDay() {
            var MonthFirstDay = showMonthFirstDay()
            return new Date(MonthFirstDay.getYear(), MonthFirstDay.getMonth() + 1, 1)
        }
    
    //下月最后一天
    function showNextLastDay() {
        var MonthFirstDay = showMonthFirstDay()
        return new Date(new Date(MonthFirstDay.getYear(), MonthFirstDay.getMonth() + 2, 1) - 86400000)
    }
    
    function Date.prototype.toString() {
        return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate();
    }

    操作日期:

    //---------------------------------------------------  
    // 判断闰年  
    //---------------------------------------------------  
    Date.prototype.isLeapYear = function()   
     {   
         return (0==this.getYear()%4&&((this.getYear()%100!=0)||(this.getYear()%400==0)));   
     }   
     
    //+---------------------------------------------------  
    //| 日期合法性验证  
    //| 格式为:YYYY-MM-DD或YYYY/MM/DD  
    //+---------------------------------------------------  
    function IsValidDate(DateStr)   
    {   
         var sDate=DateStr.replace(/(^/s+|/s+$)/g,''); //去两边空格;   
         if(sDate=='') return true;   
         //如果格式满足YYYY-(/)MM-(/)DD或YYYY-(/)M-(/)DD或YYYY-(/)M-(/)D或YYYY-(/)MM-(/)D就替换为''   
         //数据库中,合法日期可以是:YYYY-MM/DD(2003-3/21),数据库会自动转换为YYYY-MM-DD格式   
     
          var s = sDate.replace(/[/d]{ 4,4 }[/-/]{ 1 }[/d]{ 1,2 }[/-/]{ 1 }[/d]{ 1,2 }/g,'');   
     
         if (s=='') //说明格式满足YYYY-MM-DD或YYYY-M-DD或YYYY-M-D或YYYY-MM-D   
         {   
             var t=new Date(sDate.replace(//-/g,'/'));   
             var ar = sDate.split(/[-/:]/);   
     
            if(ar[0] != t.getYear() || ar[1] != t.getMonth()+1 || ar[2] != t.getDate())   
             {   
                 //alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。');   
                 return false;   
             }   
         }   
         else   
         {   
             //alert('错误的日期格式!格式为:YYYY-MM-DD或YYYY/MM/DD。注意闰年。');   
            return false;   
         }   
        return true;   
     }   
       
    //+---------------------------------------------------  
    //| 日期时间检查  
    //| 格式为:YYYY-MM-DD HH:MM:SS  
    //+---------------------------------------------------  
    function CheckDateTime(str)  
     {   
         var reg = /^(/d+)-(/d{ 1,2 })-(/d{ 1,2 }) (/d{ 1,2 }):(/d{ 1,2 }):(/d{ 1,2 })$/;   
         var r = str.match(reg);   
         if(r==null)return false;   
         r[2]=r[2]-1;   
         var d= new Date(r[1],r[2],r[3],r[4],r[5],r[6]);   
         if(d.getFullYear()!=r[1])return false;   
         if(d.getMonth()!=r[2])return false;   
         if(d.getDate()!=r[3])return false;   
         if(d.getHours()!=r[4])return false;   
         if(d.getMinutes()!=r[5])return false;   
         if(d.getSeconds()!=r[6])return false;   
         return true;   
     
    }   
      
    //+---------------------------------------------------  
    //| 取得当前日期所在月的最大天数  
    //+---------------------------------------------------  
    

    Date.prototype.MaxDayOfDate = function() {
         var myDate = this;
         var ary = myDate.toArray();
         var date1 = (new Date(ary[0], ary[1] + 1, 1));
         var date2 = date1.dateAdd(1, 'm', 1);
         var result = dateDiff(date1.Format('yyyy-MM-dd'), date2.Format('yyyy-MM-dd'));
         return result
    }

    秒Int与Time时间字符串的转换:

    function secondToTimeString(seconds) {
    var hh = parseInt(seconds / 3600).toString();
    seconds -= hh * 3600;
    var mm = Math.round(seconds / 60).toString();
    if (hh.length == 1) {
    hh = "0" + hh;
    }
    if (mm.length == 1) {
    mm = "0" + mm;
    }
    return hh + ":" + mm;
    }
  • 相关阅读:
    将备份中的数据插入到数据库中的具体步骤
    C#三层架构(获取中文拼音和给密码加密)
    C# 三层架构项目体会(1)
    leetcode——Best Time to Buy and Sell Stock
    leetcode——Binary Tree Maximum Path Sum
    leetcode——Valid Palindrome
    leetcode——Word Ladder II
    学习制作SLG游戏(一)
    leetcode——Maximum Gap
    cocos2d学习资源收集
  • 原文地址:https://www.cnblogs.com/springsnow/p/12298122.html
Copyright © 2011-2022 走看看