JavaScript:如何获取七天前,上个月,本周的日期

时间:2016-06-01 11:38:37

标签: javascript datetime momentjs

我正在构建一个函数,我将根据用户作为参数发送的内容动态生成日期。我需要为上周,本周,上个月,本月,过去7天,过去30天等案例创建日期。由于我要向DB发送和发送日期,因此我需要将它们格式化为yyyy-mm-dd。我的问题是如何获取上周末和上周开始,本周开始的日期,以及从当前日期扣除7或30的情况的正确日期。

到目前为止,这是我的代码,但它仅适用于当月的日期:

function myDate(day){
    var date = new Date();
    var dd = date.getDate() - day;
    var mm = date.getMonth()+1; //January is 0!
    var yyyy = date.getFullYear();
    if(dd<10){
        dd='0'+dd
    }
    if(mm<10){
        mm='0'+mm
    }
    var newDate = yyyy+'-'+mm+'-'+dd;

    return newDate;
}

var today = myDate(0);
var yesterday = myDate(1);
var sevenDaysAgo = myDate(7);
var thirtyDaysAgo = myDate(30);

更新代码:

如果有人需要的话,这就是我使用moment.js的方式:

var date = moment().format("YYYY-MM-DD");
var yesterday = moment().subtract(1, 'day').format('YYYY-MM-DD');
var sevenDaysAgo = moment().subtract(7, 'day').format('YYYY-MM-DD');
var thirtyDaysAgo = moment().subtract(30, 'day').format('YYYY-MM-DD');
var lastWeekStart = moment(date).weekday(-6).format('YYYY-MM-DD');
var lastWeekEnd = moment(date).weekday(1).format('YYYY-MM-DD');
var thisWeekStart = moment(date).weekday(1).format('YYYY-MM-DD');
var startOfMonth = moment().startOf('month').format('YYYY-MM-DD');
var startOfLastMonth = moment().subtract(1, 'month').startOf('month').format('YYYY-MM-DD');
var endOfLastMonth = moment().subtract(1, 'month').endOf('month').format('YYYY-MM-DD');

2 个答案:

答案 0 :(得分:3)

DIY Date操纵

对于好奇或厌恶库的人,这里有一些例子说明如何在vanilla JavaScript中创建自己的函数,为你做这些计算:

/* Define new prototype methods on Date object. */
// Returns Date as a String in YYYY-MM-DD format.
Date.prototype.toISODateString = function () {
  return this.toISOString().substr(0,10);
};

// Returns new Date object offset `n` days from current Date object.
Date.prototype.toDateFromDays = function (n) {
  n = parseInt(n) || 0;
  var newDate = new Date(this.getTime());
  newDate.setDate(this.getDate() + n);
  return newDate;
};

// Returns new Date object from start of week of current Date object
// optionally offset `n` weeks from week of current Date object.
Date.prototype.toStartOfWeek = function (n) {
  var newDate = new Date(this.getTime());
  newDate.setDate(this.getDate() - this.getDay());
  return n ? newDate.toDateFromDays(n * 7) : newDate;
};

// Returns new Date object from start of month of current Date object
// optionally offset `n` months from month of current Date object.
Date.prototype.toStartOfMonth = function (n) {
  n = parseInt(n) || 0;
  var newDate = new Date(this.getTime());
  newDate.setMonth(this.getMonth() + n, 1);
  return newDate;
};

/* Instantiate a Date. */
var today = new Date();

/* Chain all the things. */
console.log(
  'Today:               ', today.toISODateString()
);
console.log(
  '7 days ago:          ', today.toDateFromDays(-7)
                                .toISODateString()
);
console.log(
  '30 days ago:         ', today.toDateFromDays(-30)
                                .toISODateString()
);
console.log(
  '90 days from now:    ', today.toDateFromDays(90)
                                .toISODateString()
);
console.log(
  'Start of this week:  ', today.toStartOfWeek()
                                .toISODateString()
);
console.log(
  'End of this week:    ', today.toStartOfWeek(1)
                                .toDateFromDays(-1)
                                .toISODateString()
);
console.log(
  'Start of last week:  ', today.toStartOfWeek(-1)
                                .toISODateString()
);
console.log(
  'End of last week:    ', today.toStartOfWeek()
                                .toDateFromDays(-1)
                                .toISODateString()
);
console.log(
  'Start of next week:  ', today.toStartOfWeek(1)
                                .toISODateString()
);
console.log(
  'End of next week:    ', today.toStartOfWeek(2)
                                .toDateFromDays(-1)
                                .toISODateString()
);
console.log(
  'Start of this month: ', today.toStartOfMonth()
                                .toISODateString()
);
console.log(
  'End of this month:   ', today.toStartOfMonth(1)
                                .toDateFromDays(-1)
                                .toISODateString()
);
console.log(
  'Start of last month: ', today.toStartOfMonth(-1)
                                .toISODateString()
);
console.log(
  'End of last month:   ', today.toStartOfMonth()
                                .toDateFromDays(-1)
                                .toISODateString()
);
console.log(
  'Start of next month: ', today.toStartOfMonth(1)
                                .toISODateString()
);
console.log(
  'End of next month:   ', today.toStartOfMonth(2)
                                .toDateFromDays(-1)
                                .toISODateString()
);

MDN documentation for the Date constructor function有关本示例中使用的本机方法的更多信息。

答案 1 :(得分:1)

实际上我没有得到错误,但如果我需要按照提供的问题预先格式化日期。

 var startOfWeek = moment().day(1).format(); // day(0) if in your country start of week is on Sunday
 var final = moment(startOfWeek).format('YYYY-MM-DD');