如何用JavaScript检查日期是否在这一周?

Sop*_*Men 2 javascript datetime date angularjs

我有这个日期“ 2016-04-23T11:45:00Z”,我想在这个星期检查这个日期吗?

谢谢,

Jam*_*iec 5

日期很难,我总是建议使用专用于日期处理的库,因为它可以减少代码出错的机会。

MomentJS是一个很好的。

var now = moment();
var input = moment("2016-04-17T11:45:00Z");
var isThisWeek = (now.isoWeek() == input.isoWeek())
Run Code Online (Sandbox Code Playgroud)


Mic*_*nch 5

这似乎对我有用。

function isDateInThisWeek(date) {
  const todayObj = new Date();
  const todayDate = todayObj.getDate();
  const todayDay = todayObj.getDay();

  // get first date of week
  const firstDayOfWeek = new Date(todayObj.setDate(todayDate - todayDay));

  // get last date of week
  const lastDayOfWeek = new Date(firstDayOfWeek);
  lastDayOfWeek.setDate(lastDayOfWeek.getDate() + 6);

  // if date is equal or within the first and last dates of the week
  return date >= firstDayOfWeek && date <= lastDayOfWeek;
}

const date = new Date();
const isInWeek = isDateInThisWeek(date);
Run Code Online (Sandbox Code Playgroud)


小智 2

<div ng-app="myApp">
<div class="container" ng-controller="Ctrl_List">

    <h1>{{currentDate}}</h1>
    <h1>{{numberCurrentDateWeeks}}</h1>

    <h1>{{yourDate}}</h1>
    <h1>{{numberYourDateWeeks}}</h1>

 </div>
</div>
Run Code Online (Sandbox Code Playgroud)

......

angular.module('myApp', [])
.controller("Ctrl_List", ["$scope", "$filter", function(s, $filter) {
  s.yourDate = '2016-04-23T11:45:00Z'
  s.currentDate = new Date();

  s.numberCurrentDateWeeks = $filter('date')(s.currentDate, "w");
  s.numberYourDateWeeks = $filter('date')(s.yourDate, "w");

}]);
Run Code Online (Sandbox Code Playgroud)

然后你就得到了周数,只需比较或做任何你喜欢的事情

干杯!