2017-08-03 168 views
1

我有一些數據,所以從一個datepicker:計算結束日期與禁用日期週數和

$disabled_dates = "08/10/2017, 08/17/2017"; 
$start_date = "08/03/2017"; 
$num_of_weeks = "20"; 

我想計算的終止日期基於關閉$start_date$num_of_weeks

我知道這是可能的new Date(),但我不知道如何解釋$disabled_dates

+0

你需要考慮什麼?它對我不清楚。殘疾人日期應該被忽略,如果是這樣的開始或結束?如果在20周的範圍內找到日期,是否應該添加日期? – Yolo

回答

2

strtotime()對於這樣的事情來說是一個非常有用的功能。它接受各種各樣的自然語言和日期/時間輸入。

20從正好現在周從那天

echo date('c',strtotime('08/03/2017 +20 weeks'))."\n"; 

你的答案PHP開始

echo date('c',strtotime('+20 weeks'))."\n"; 

20周:

$disabled_dates = "08/10/2017, 08/17/2017"; 
$start_date = "08/03/2017"; 
$num_of_weeks = "20"; 

$the_end = strtotime($start_date.' GMT +'.$num_of_weeks.' weeks'); 

//make all the disabled dates into timestamps for easy comparison later 
$disabled_dates_array = array(); 
foreach(explode(',', $disabled_dates) as $date){ 
    $disabled_dates_array[] = strtotime(trim($date).' GMT'); 
} 

//now compare and delay the end date if needed 
foreach($disabled_dates_array as $timestamp){ 
    //if there was a disabled date before the end, add a day's worth of seconds 
    //strtotime() returns false if it can't parse the date, so make sure it's truthy 
    if($timestamp && $timestamp <= $the_end){ 
    $the_end += 86400; 
    } 
} 

$enddate = date('m/d/Y',$the_end); 

編輯1:將GMT添加到所有strtotim e()轉換,以避免夏令時更改日期之間秒數的問題。由於夏令時,有些日子是23小時,有些是25。在unix時間,Leap seconds不是問題。

編輯2:搶答的JavaScript

var disabled_dates = "08/10/2017, 08/17/2017"; 
var start_date = "08/03/2017"; 
var num_of_weeks = "20"; 

var the_end = Date.parse(start_date + ' GMT') + parseInt(num_of_weeks)*7*86400*1000; 

//in javascript Date.parse is similar to php's strtotime, 
//but it returns milliseconds instead of seconds 
disabled_dates = disabled_dates.split(", "); 
for(var i = 0, len = disabled_dates.length; i < len; i++){ 
    disabled_dates[i] = Date.parse(disabled_dates[i] + ' GMT'); 
    if(disabled_dates[i] && disabled_dates[i] <= the_end){ 
the_end += 86400000; 
    } 
} 

the_end = new Date(the_end); 
var enddate = ('0' + (the_end.getUTCMonth() + 1)).substr(-2) + '/' + ('0' + the_end.getUTCDate()).substr(-2) + '/' + the_end.getUTCFullYear(); 
console.log(enddate); 

在這裏,我遇到了夏令時間問題,因爲

Sun Oct 29 2017 00:00:00 GMT+0100 (GMT Daylight Time) + 24 hours = 
Sun Oct 29 2017 23:00:00 GMT+0000 (GMT Standard Time) 

所以添加 'GMT'(GMT標準時間)在日期結束時很重要,否則結果可能會關閉一天。

This video對如何使時間變得複雜提供了一些見解。

+0

真棒,謝謝!有沒有更好的方法來使用jQuery或Javascript做到這一點? – 626

+0

@ 626我在javascript中添加了一個解決方案,並編輯了我的答案以處理由夏時制引入的可能錯誤。 –

0

我不知道如果有一個更簡單的方法,但這是誰,我會做到這一點:

// Put dates into array or split the string 
$disabled = array(new DateTime('2012-08-01'),new DateTime('2017-09-19')); 

$end_date = $date->add(new DateInterval('P'.$num_of_weeks.'D')); 
$range = new DatePeriod($start_date, new DateInterval('P1D'),$end_date); 

// remove disabled days 
foreach($range as $date){ 
    if(in_array($date,$disabled)) 
     $end_date = $end_date->sub(new DateInterval('P1D')); 
} 

代碼沒有測試,但它應該工作。如果沒有,讓我知道xD。

希望有所幫助。

相關問題