0

我一直在尝试计算平日中某物的年龄。我已经尝试过这个问题中详述的方法,给定日期范围如何计算部分或全部在该范围内的周末数?但它似乎不适合我的用例。

一个项目DATETIME在数据库中创建,如果创建日期超过 2 天,我需要将其标记为旧。但是,客户要求该年龄仅计算工作日(周一至周五)并排除周六+周日。

到目前为止,我的伪代码如下所示,

now - created_datetime = number_of_days
for(i number_of_days)
  if(created_datetime - i)
    is a weekday, then age++

必须有一种更清洁的方法来实现这一目标吗?好像一个项目会变得很旧,循环遍历它的每一天,寻找一个周末的日子会对速度产生相当大的影响。

任何想法都会很棒!谢谢

4

2 回答 2

1

您只需查看过去 7 天的数据,即可了解工作日的确切年龄。

这是直觉:

从对象的总年龄中减去其生命周期中的周末数。请注意,每 7 天正好有 2 个周末。再加上剩余天数(不在一周内的天数)的周末天数,您必须计算其生命周期中的周末天数。从实际年龄中减去得到工作日年龄。

int weekendCount = 0;
// Check the remainder days that are not in a full week.
for (int i = totalAge % 7; i < 7; i++) {
    if (created_datetime - i is weekend) {
        weekendCount++;
    }
}

weekdayAge = totalNumberOfDays  - (((totalNumberOfDays / 7) * 2) + weekendCount);

请注意,除法是整数除法。

于 2010-04-12T15:37:20.607 回答
0

I'm sure you can do this with some math and a bit of careful thought. You need to check what day of the week the item was created and what day of the week it currently is. First, you calculate the number of days old it is, as I'm sure you were doing at first.

// if today is saturday, subtract 1 from the day. if its sunday, subtract 2
if (now() is sunday) $now = now() - 2 days;
if (now() is saturday) $now = now() - 1 day;

// same thing for $date posted.  but adding 1 or 2 days
if ( $date is saturday) $date = $date + 2;
if ( $date is sunday) $date = $date + 1;

// get days difference
$days = $today - $date;
// have to subtract 2 days for every 7
$days = $days - floor($days/7)*2

You'd have to check if that works. Maybe you can do the calculation without moving your date to before/after the weekend. It may not be perfect, but its the right idea. No need to iterate.

于 2010-04-12T15:36:32.637 回答