• 技术文章 >web前端 >js教程

    JS中常用的时间方法有哪些

    一个新手一个新手2017-09-19 10:40:31原创857
    这篇文章主要是分享几个比较常用的时间方法:

    //格式化日期

    Date.prototype.Format = function(fmt) {

    var o = {

    "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+)/.test(fmt)) {

    fmt = fmt.replace(RegExp.$<span class="hljs-number">1</span>, (<span class="hljs-keyword">this</span>.getFullYear() + <span class="hljs-string">""</span>).substr(<span class="hljs-number">4</span> - RegExp.$1.length));

    };

    for(var k in o) {

    if(new RegExp("(" + k + ")").test(fmt)) {

    fmt = fmt.replace(RegExp.$<span class="hljs-number">1</span>, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));

    }

    };

    return fmt;

    };

    //获取前几天或后几天的日期;正数表示前d天,负数表示后d天

    Date.prototype.getWitchDate=function(d){

    if(/(\d)/.test(d)){

    d=this.getDate()+d;

    this.setDate(d)

    };

    return this;

    };

    //获取某月有多少天

    Date.prototype.getMonthTotalDay=function(){

    this.setDate(32);

    return 32-this.getDate();

    };

    //获取周几

    Date.prototype.getWeek=function(d){

    var week=['星期一','星期二','星期三','星期四','星期五','星期六','星期天'];

    if(typeof d !== 'undefined'){

    return week[parseInt(d)%7];

    };

    return week[this.getDay()]; };

    //获取两个日期的时间差,单位秒

    Date.prototype.getDateSecond=function(d){

    if(typeof d === 'string'){

    d=new Date(d);

    }

    var t1=this.getTime();

    var t2=d.getTime();

    return Math.floor(Math.abs(t1-t2)/1000);

    };

    用法:

    var h = '当前时间是' + d.Format('yyyy-MM-dd hh:mm:ss')+'</br>';

    h += '3天前是' + d.getWitchDate(-3).Format('yyyy-MM-dd hh:mm:ss')+'</br>';

    h += '9月份有' + d.getMonthTotalDay()+'天</br>';

    h += '今天是' + d.getWeek()+'</br>';

    h += '今天距离2016年9月15日相差' + d.getDateSecond('2016/9/15') +'秒'

    以上就是JS中常用的时间方法有哪些的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:javascript 哪些 方法
    上一篇:用ionic实现无限轮播与点击跳转 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • 聊聊Node中怎么用async函数• 浅析Angular中怎么结合使用FormArray和模态框• react 怎么实现按需加载• react怎么实现滚动条• 一文聊聊node文件的读写操作
    1/1

    PHP中文网