获取本周/月第一天,最后一天,往前推几天,往后延几天

html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script src="date.js"></script>
    <script>
        var d = new getDate();
        alert(d.firstWeekDay());        //获取本周第一天日期
        alert(d.finaWeekDay());     //获取本周最后一天日期
        alert(d.firstDay());    //获取本月第一天
        alert(d.endDay());  //获取本月最后一天
        alert(d.preDay(6)); //日期往前推6天
        alert(d.nextDay(3));    //日期往后推3天
    </script>
</body>
</html>

date.js

function getDate(){
    this.date = new Date();
    this.yy = this.date.getFullYear();
    this.mm = this.date.getMonth() + 1;
    this.dd = this.date.getDate();
    this.ww = ((this.date.getDay() != 0) ? this.date.getDay() : 7);
}
getDate.prototype =  {
    //获取本周第一天日期
    "firstWeekDay": function(){
        var nd = this.date.valueOf() - (this.ww - 1) * 24 * 60 * 60 * 1000;
        nd = new Date(nd);
        return this.dateToString(nd);
    },
    //获取本周最后一天日期
    "finaWeekDay": function(){
        var nd = this.date.valueOf() + (7 - this.ww) * 24 * 60 * 60 * 1000;
        nd = new Date(nd);
        return this.dateToString(nd);
    },
    // 获取本月第一天
    "firstDay": function(){
        return this.yy + "-" + this.zero(this.mm) + "-01";
    },
    // 获取本月最后一天
    "endDay": function(){
        var nextMonthFirstDay = new Date(this.yy, this.mm, 1);
        var oneDay = 1000 * 60 * 60 * 24;
        return this.yy + "-" + this.zero(this.mm) +"-"+ this.zero(new Date(nextMonthFirstDay - oneDay).getDate());
    },
    //日期往前推天数
    "preDay": function(day){
        var nd = this.date.valueOf() - day * 24 * 60 * 60 * 1000;
        nd = new Date(nd);
        return this.dateToString(nd);
    },
    //日期往后推天数
    "nextDay": function(day){
        var nd = this.date.valueOf() + day * 24 * 60 * 60 * 1000;
        nd = new Date(nd);
        return this.dateToString(nd);
    },
    "dateToString": function(date){
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        return year + "-" + this.zero(month) + "-" + this.zero(day);
    }, 
    "zero": function(num){
        return (num<=9)?("0"+num):num;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值