2010-04-12 47 views
0

我一直在努力計算平日裏的東西的年齡。我試過了這個問題中詳細描述的方法Given a date range how to calculate the number of weekends partially or wholly within that range?,但它似乎不適合我的用例。只在工作日計算一件物品的年齡只有

一個項目在數據庫中創建了一個DATETIME,如果創建的日期超過2天,我需要將其標記爲舊。然而,客戶要求該年齡僅計算週日(週一至週五)並排除週六+日。

到目前爲止,我的僞代碼如下所示,

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

必須有實現這一目標的一個更清潔的方式?就好像一件物品變得非常老舊,每一天都在變老,尋找一個週末的日子會對速度產生很大的影響。

任何想法都會很棒!謝謝

+1

你閱讀本:http://stackoverflow.com/questions/336127/calculate-business-days-in-php – webbiedave 2010-04-12 15:30:49

+0

沒有,我錯過了一個,只是閱讀,現在,看起來很有希望 – 2010-04-12 15:44:21

+0

這個問題已經整理我!好東西,非常感謝 – 2010-04-12 15:48:11

回答

0

我相信你可以用一些數學和一些仔細的想法做到這一點。您需要檢查一週中的哪一天創建了該項目,以及它當前的星期幾。首先,你計算了它的年齡,因爲我確信你一開始就是這麼做的。

// 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 

你必須檢查是否有效。也許你可以在不將日期移動到週末前後的情況下進行計算。它可能不完美,但它是正確的想法。無需迭代。

+0

這不包括一週中所有日子的正確年齡。例如,如果創建的日期是星期五,而今天是星期一,則表示它的日期是3天,但只有1天。 – 2010-04-12 15:39:14

+0

就像我說的,我沒有弄清楚細節。但你只需要擔心編碼這些邊緣情況的一些,你會沒事的。總體思路是一樣的。做天 - 地板($天/ 7)* 2並處理邊緣情況 – pocketfullofcheese 2010-04-12 16:09:33

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

請注意,除法是一個整數除法。