get all day between 2 timestamp

dc200687 注册会员
2023-01-25 22:41

The sample timestamps are UTC, but the working is with local dates so the following does the same. This may produce different results on hosts with different timezone offsets. If you want all UTC, then just change all the methods to UTC methods (setHours to setUTCHours, getDate to getUTCDate, etc.).

You can convert the day name to number much more simply using an array and indexOf rather than a long switch block.

Getting the first instance of a particular day is fairly straight forward too, though you have to check that it's not before the start (e.g. if the date range is Thu to Mon and you want Sun, then then the algorithm finds the Sun before Thu, not after). So there's a check and if it's before start, a week is added.

Then it's just a matter of checking against the end date and pushing a timestamp into the result array for each day, then adding 7 days, etc.

You can do it all using a library, but it's not that hard in plain JS:

function getDaysBetween(d1, d2, day) {
  // Convert day name to number
  let days = ['su','mo','tu','we','th','fr','sa'];
  let dayNum = days.indexOf(day.toLowerCase().substr(0,2));
  // Convert timestamps to Dates and set to start of day
  let start = new Date(d1);
  let end = new Date(d2);
  // Get first instance of day name in same week as start
  let d = new Date(start);
  d.setDate(d.getDate() - d.getDay() + dayNum);
  // If before start, add 7 days
  if (d < start) d.setDate(d.getDate() + 7);
  let result = [];
  while (d <= end) {
    d.setDate(d.getDate() + 7)
  return result;

let start = '2021-12-20T07:50:00.000Z';
let end = '2021-12-25T07:50:00.000Z'; 
let day = 'Friday';

console.log(getDaysBetween(start, end, day));

About the Author

Question Info

Publish Time
2023-01-25 22:41
Update Time
2023-01-25 22:41