【问题标题】:JavaScript: How to get dates for seven days ago, last month, this weekJavaScript:如何获取 7 天前、上个月、本周的日期
【发布时间】:2016-06-01 11:38:37
【问题描述】:

我正在构建一个函数,我将根据用户作为参数发送给它的内容动态生成日期。我需要为上周、本周、上个月、本月、过去 7 天、过去 30 天等案例创建日期。由于我要从和到日期发送到数据库,因此我需要将它们格式化为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');

【问题讨论】:

  • 我建议你使用moment.js
  • Moment.js 是进行您想要的计算的最佳解决方案。
  • 我已经添加了 moment.js 并开始使用它,更新了我目前正在使用的问题。

标签: javascript datetime momentjs


【解决方案1】:

DIYDate操纵

对于好奇或厌恶图书馆的人,这里有一些示例展示了如何在 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 了解有关此示例中使用的本机方法的更多信息。

【讨论】:

  • 年初和年末怎么样?
  • @Smith 我没有包括那个例子,因为 OP 没有要求它。但是我已经演示了在Date 原型上创建自己的计算方法的模式,因此推断.toStartOfYear(以及,如果需要,.toEndOfYear)的解决方案应该是微不足道的。提示:月份和日期将是静态的(1 月 1 日 [01-01] 表示年初;12 月 31 日 [12-31] 表示年底),并且存在获取年份的本地方法(请参阅:@987654322 @)。 :)
【解决方案2】:

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

 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');

【讨论】:

    猜你喜欢
    • 2011-04-14
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 2012-03-19
    • 2010-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多