繁体   English   中英

如何检查javascript中的日期是否在本周?

[英]How to check if date is in this week in javascript?

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

谢谢,

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

MomentJS是一个不错的选择。

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

编辑:请注意,截至 2020 年,对于新项目来说可能不是一个好的选择

这似乎对我有用。

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

......

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

}]);

然后你得到了周数只是比较或做任何你喜欢的

干杯!

可能不是最佳解决方案,但我认为它非常易读:

function isThisWeek (date) {
  const now = new Date();

  const weekDay = (now.getDay() + 6) % 7; // Make sure Sunday is 6, not 0
  const monthDay = now.getDate();
  const mondayThisWeek = monthDay - weekDay;

  const startOfThisWeek = new Date(+now);
  startOfThisWeek.setDate(mondayThisWeek);
  startOfThisWeek.setHours(0, 0, 0, 0);

  const startOfNextWeek = new Date(+startOfThisWeek);
  startOfNextWeek.setDate(mondayThisWeek + 7);

  return date >= startOfThisWeek && date < startOfNextWeek;
}

您可以在没有任何库的情况下通过检查date.getTime() (自纪元以来的毫秒数)是否在上周一和下周一之间来做到这一点:

const WEEK_LENGTH = 604800000;

function onCurrentWeek(date) {

    var lastMonday = new Date(); // Creating new date object for today
    lastMonday.setDate(lastMonday.getDate() - (lastMonday.getDay()-1)); // Setting date to last monday
    lastMonday.setHours(0,0,0,0); // Setting Hour to 00:00:00:00
    


    const res = lastMonday.getTime() <= date.getTime() &&
                date.getTime() < ( lastMonday.getTime() + WEEK_LENGTH);
    return res; // true / false
}

(一周毫秒 = 24 * 60 * 60 * 1000 * 7 = 604,800,000)

此链接解释了如何在不使用任何 js 库的情况下执行此操作。 https://gist.github.com/dblock/1081513

防止链接死亡的代码:

function( d ) { 

  // Create a copy of this date object  
  var target  = new Date(d.valueOf());  

  // ISO week date weeks start on monday  
  // so correct the day number  
  var dayNr   = (d.getDay() + 6) % 7;  

  // Set the target to the thursday of this week so the  
  // target date is in the right year  
  target.setDate(target.getDate() - dayNr + 3);  

  // ISO 8601 states that week 1 is the week  
  // with january 4th in it  
   var jan4    = new Date(target.getFullYear(), 0, 4);  

  // Number of days between target date and january 4th  
  var dayDiff = (target - jan4) / 86400000;    

  // Calculate week number: Week 1 (january 4th) plus the    
  // number of weeks between target date and january 4th    
  var weekNr = 1 + Math.ceil(dayDiff / 7);    

  return weekNr;    

}

我设法用这个简单的技巧做到了,没有任何外部库。 考虑到星期一是一周的第一天,function 将日期字符串作为参数,并在检查这一天是否确实在当前周之前进行验证。

  function isInThisWeek(livr){
const WEEK = new Date()

// convert delivery date to Date instance
const DATEREF = new Date(livr)

// Check if date instance is in valid format (depends on the function arg) 
if(DATEREF instanceof Date && isNaN(DATEREF)){ 
  console.log("invalid date format")
  return false}

// Deconstruct to get separated date infos
const [dayR, monthR, yearR] = [DATEREF.getDate(), DATEREF.getMonth(), DATEREF.getFullYear()]

// get Monday date 
const monday = (WEEK.getDate() - WEEK.getDay()) + 1

// get Saturday date
const sunday = monday + 6

// Start verification
if (yearR !== WEEK.getFullYear())  { console.log("WRONG YEAR"); return false }
if (monthR !== WEEK.getMonth()) { console.log("WRONG MONTH"); return false }
if(dayR >= monday && dayR <= sunday) { return true }
else {console.log("WRONG DAY"); return false}

}

在评论中我看到你说你的一周从星期一开始。

在那种情况下,我想计算这两个日期的 ISO 周数并查看是否为这两个日期获得相同的周数是个好主意。

要计算ISO week number ,请检查答案:

如果其他人的一周从星期日开始,您可以使用答案相应地计算周数。

那么你可以这样做:

function isSameWeek(date1, date2) {
   return date1.getWeekNumber() === date2.getWeekNumber();
}
const isDateInThisWeek = (date) => {
  const today = new Date();
  
  //Get the first day of the current week (Sunday)
  const firstDayOfWeek = new Date(
    today.setDate(today.getDate() - today.getDay())
  );

  //Get the last day of the current week (Saturday)
  const lastDayOfWeek = new Date(
    today.setDate(today.getDate() - today.getDay() + 6)
  );

  //check if my value is between a minimum date and a maximum date
  if (date >= firstDayOfWeek && date <= lastDayOfWeek) {
    return true;
  } else {
    return false;
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM