【问题标题】:Calculate last week start date in JavaScript (not -7 days ago)用 JavaScript 计算上周开始日期(不是 -7 天前)
【发布时间】:2015-09-11 03:08:54
【问题描述】:

我有一个活动记录列表,它们都有日期并显示在活动流中。

我想根据记录的创建日期在记录之间插入分隔符 DIV。

我想显示一个带有文本 本周 的 DIV,它将采用当前一周的开始日期(不超过 7 天),然后我可以显示自该日期以来创建的所有记录。

我还想为 上周 做一个,这意味着我需要获取上周开始日期和上周结束日期的 Date 值。或者开始日期 +7 就可以了。

然后我有一个 JavaScript 库来比较日期范围。我可以传入开始日期和结束日期,并确定第三个日期是否在日期范围内,这将使我知道在每个日期部分下显示哪些记录。

所以我请求帮助计算:

一周的开始日期是大多数日历中的星期日或星期一

  • 当前周开始日期
  • 上周开始日期和结束日期

此外,如果我能提供帮助,我不希望将庞大的 Moment.js 库用于这些少数日期操作。

感谢您的帮助

下图显示了我试图通过日期部分来打破我的记录...


用于 DateTime 比较和检查日期是否在 2 个日期范围之间的日期库!

// Source: http://stackoverflow.com/questions/497790
var dates = {
  convert: function(d) {
    // Converts the date in d to a date-object. The input can be:
    //   a date object: returned without modification
    //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
    //   a number     : Interpreted as number of milliseconds
    //                  since 1 Jan 1970 (a timestamp)
    //   a string     : Any format supported by the javascript engine, like
    //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
    //  an object     : Interpreted as an object with year, month and date
    //                  attributes.  **NOTE** month is 0-11.
    return (
      d.constructor === Date ? d :
      d.constructor === Array ? new Date(d[0], d[1], d[2]) :
      d.constructor === Number ? new Date(d) :
      d.constructor === String ? new Date(d) :
      typeof d === "object" ? new Date(d.year, d.month, d.date) :
      NaN
    );
  },
  compare: function(a, b) {
    // Compare two dates (could be of any type supported by the convert
    // function above) and returns:
    //  -1 : if a < b
    //   0 : if a = b
    //   1 : if a > b
    // NaN : if a or b is an illegal date
    // NOTE: The code inside isFinite does an assignment (=).
    return (
      isFinite(a = this.convert(a).valueOf()) &&
      isFinite(b = this.convert(b).valueOf()) ?
      (a > b) - (a < b) :
      NaN
    );
  },
  inRange: function(d, start, end) {
    // Checks if date in d is between dates in start and end.
    // Returns a boolean or NaN:
    //    true  : if d is between start and end (inclusive)
    //    false : if d is before start or after end
    //    NaN   : if one or more of the dates is illegal.
    // NOTE: The code inside isFinite does an assignment (=).
    return (
      isFinite(d = this.convert(d).valueOf()) &&
      isFinite(start = this.convert(start).valueOf()) &&
      isFinite(end = this.convert(end).valueOf()) ?
      start <= d && d <= end :
      NaN
    );
  },

  // Subtract number of months from current month
  // dates.subtractMonth(1)
  subtractMonth: function(numberOfMonths) {
    //var d = this;
    var d = new Date();
    d.setMonth(d.getMonth() - numberOfMonths);
    d.setDate(1);
    return d;
  }

};

///////////////////////////////////////////////////////////////////////////

我的示例 JSON 数据的日期将与其他日期进行比较以确定何时将日期部分标题注入循环

var task_activities = [{"id":1,"name":"record 1","date_time":"1\/5\/2015"},{"id":2,"name":"record 2","date_time":"1\/9\/2015"},{"id":3,"name":"record 3","date_time":"1\/13\/2015"},{"id":4,"name":"record 4","date_time":"1\/17\/2015"},{"id":5,"name":"record 5","date_time":"1\/21\/2015"},{"id":6,"name":"record 6","date_time":"1\/25\/2015"},{"id":7,"name":"record 7","date_time":"1\/29\/2015"},{"id":8,"name":"record 8","date_time":"2\/1\/2015"},{"id":9,"name":"record 9","date_time":"2\/5\/2015"},{"id":10,"name":"record 10","date_time":"2\/9\/2015"},{"id":11,"name":"record 11","date_time":"2\/13\/2015"},{"id":12,"name":"record 12","date_time":"2\/17\/2015"},{"id":13,"name":"record 13","date_time":"2\/21\/2015"},{"id":14,"name":"record 14","date_time":"2\/25\/2015"},{"id":15,"name":"record 15","date_time":"2\/29\/2015"},{"id":16,"name":"record 16","date_time":"3\/1\/2015"},{"id":17,"name":"record 17","date_time":"3\/5\/2015"},{"id":18,"name":"record 18","date_time":"3\/9\/2015"},{"id":19,"name":"record 19","date_time":"3\/13\/2015"},{"id":20,"name":"record 20","date_time":"3\/17\/2015"}];



// Loop over each Task Activity record and generate HTML
$.each(task_activities, function(i, activity) {
    console.log(activity.date_time);
}); // end each

【问题讨论】:

  • 只需从日期减去 1,直到日期对象告诉您星期几是您想要的一周开始。
  • @Pointy 谢谢我没想到!同样,一旦我减去以获得本周的开始,那么我可以简单地减去 7 天来获得上周的开始,等等......会比我之前的要容易得多,谢谢
  • JavaScript Date 的东西不是很复杂,但是做这样简单的东西确实很容易:)

标签: javascript date datetime


【解决方案1】:

首先,subtractMonth 函数存在缺陷,3 月 31 日减去 1 个月返回 3 月 1 日。

如果您想找到给定日期一周的第一天,只需从星期天开始的星期的日期中减去天数,或者从星期一开始的星期减去星期天或星期天减去 6 天:

/**
**  @param {Date} date - date to get start of week for
**  @param {Boolean} mondayStart - falsey for Sunday as first day of week,
**                                 truthy for Monday as first day of week
**  @returns {Date} - date for first day of week
*/
function getStartOfWeek(date, mondayStart) {

  // copy date
  var d = new Date(+date);
  // days to previous Sunday
  var shift = d.getDay();

  // Adjust shift if week starts on Monday
  if (mondayStart) {
    shift = shift? shift - 1 : 6;
  }

  // Shift to start of week
  d.setDate(d.getDate() - shift);
  return d;
}

如果您希望 subtractMonth 函数起作用,请说出您希望它做什么。

编辑

作为一项奖励功能,这里有一个减月功能,我认为它的工作原理是这样的:

/*
** @param {number} numberOfMonths - number of months to add to date
** @param {Date} date - date to subract months from
** @returns {Date} - the passed in date object with the specified number of months subtracted
*/
function subtractMonth (numberOfMonths, date) {

  // If date not supplied, default to today
  var d = date || new Date();

  // Get the date
  var day = d.getDate();

  // Subtract the months
  d.setMonth(d.getMonth() - numberOfMonths);

  // If date has changed, was too big for month and has rolled over
  // into next month, so set to last day of previous month
  if (day != d.getDate) d.setDate(0);
  return d;
}

【讨论】:

  • 非常感谢,它们为我的小日期库提供了很好的补充。减月函数似乎工作得很好,因为它具有正确的月份结束日期。一开始我不确定的一件事是例如从现在减去 1 个月显示 Jul 31 并且因为我们几乎是 9 月中旬,所以它似乎可能跳过了 8 月,但我意识到这是一个棘手的问题,因为很多人会有不同的需求。最后,我仍然不能 100% 确定最终结果需要什么,但是....继续...
  • 使用我的dates.inRange(d, start, end)函数并插入这些新的日期值,同时在上面迭代我的JSON,我可以确定每条记录的位置...YesterdayThis weekLast Week,'本月早些时候, 'Last Month。一旦我得到我需要的日期值,我仍然不确定我将如何在我的记录之间插入 1 个日期标题。例如,如果 5 条记录都在 This week 的范围内,我只需要在这 5 条记录以上插入日期标题 This Week 1 次。在这 5 条记录之后,它可能会达到 Last Week.. 下的记录
  • ....不确定我是否说得通。我在上面发布的图片可能比文字解释得更好。你的代码是缺失的部分,所以谢谢!
  • 我在想也许我可以做一个switch() 并在其中包含我的每个日期条件。然后,我的 JSON 记录日期将被传递到开关中,并确定它适合的时间(本周、上周等)。你有什么想法我可以为每个组插入 yhis 日期标题 DIV,它将位于其下的每个记录的顶部。我在这里有一个小提琴,我的 JSON 被迭代,所有这些日期函数都可以玩。 jsfiddle.net/jasondavis/Lq3ntrdu
  • 我的一个想法是可能为每个日期部分创建一个标志变量,一旦有 1 个 JSON 记录匹配,我将指示该日期部分标题的标志设置为不再需要创建。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
相关资源
最近更新 更多