javascript - 在 JavaScript 中计算上周开始日期(不是 -7 天前)

标签 javascript date datetime

我有一个事件记录列表,其中所有记录都有日期并显示在事件流中。

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

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

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

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

所以我请求帮助计算:

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

  • 本周开始日期
  • 上周开始日期和结束日期

此外,如果可以的话,我不喜欢使用庞大的 Moment.js 库来进行这几个日期操作。

感谢您的帮助

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

enter image description here

<小时/>

用于日期时间比较并检查日期是否在 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 数据,其中包含一个日期,该数据将与其他日期进行比较,以确定何时将日期部分 header 插入循环

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

最佳答案

首先,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;
}

关于javascript - 在 JavaScript 中计算上周开始日期(不是 -7 天前),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32514861/

相关文章:

php - 在 PHP 后端和 iOS 之间共享日期的最佳方式是什么?

javascript - 无法更改表中动态附加行的样式?

javascript - 使 img 标签完全填充页面而不创建滚动条

javascript - 当模态视图打开时禁用主体滚动

php - 将小数精度的MSSQL时间转换为PHP时间和MySQL DateTime

asp.net-mvc-3 - ASP.Net MVC Razor 从 DateTime 属性中删除时间

java - 时间戳格式匹配

javascript - 使用来自多个文本框的输入形成一系列地址列表

jquery - flot 根据时间戳显示 flot 中的日期

sql-server - SQL Server 如何从日期获取当前季度的字段计数?