void foo(vector<int> test)
вектор будет передан по значению в этом.
У вас есть больше способов передать векторы в зависимости от контекста: -
1 ) Передайте по ссылке: - Это позволит функции foo изменить содержимое вашего вектора.
2) Передача по const-reference: - Это эффективно и надежно, когда вы не хотите, чтобы функция меняла содержимое вектора .
Объект DateTime + PHP5 полезен, потому что это - время прыжка и знающий переход на летнее время, но требуется некоторое расширение для реального решения проблемы. Я записал следующее для решения подобной проблемы. find_WeekdaysFromThisTo () метод "в лоб", но он работает обоснованно быстро, если Ваш отрезок времени составляет меньше чем 2 года.
$tryme = new Extended_DateTime('2007-8-26');
$newer = new Extended_DateTime('2008-9-1');
print 'Weekdays From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_WeekdaysFromThisTo($newer) ."\n";
/* Output: Weekdays From 2007-08-26 To 2008-09-01: 265 */
print 'All Days From '.$tryme->format('Y-m-d').' To '.$newer->format('Y-m-d').': '.$tryme -> find_AllDaysFromThisTo($newer) ."\n";
/* Output: All Days From 2007-08-26 To 2008-09-01: 371 */
$timefrom = $tryme->find_TimeFromThisTo($newer);
print 'Between '.$tryme->format('Y-m-d').' and '.$newer->format('Y-m-d').' there are '.
$timefrom['years'].' years, '.$timefrom['months'].' months, and '.$timefrom['days'].
' days.'."\n";
/* Output: Between 2007-08-26 and 2008-09-01 there are 1 years, 0 months, and 5 days. */
class Extended_DateTime extends DateTime {
public function find_TimeFromThisTo($newer) {
$timefrom = array('years'=>0,'months'=>0,'days'=>0);
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$timefrom['years'] = $this->find_YearsFromThisTo($testnewer);
$mod = '-'.$timefrom['years'].' years';
$testnewer -> modify($mod);
$timefrom['months'] = $this->find_MonthsFromThisTo($testnewer);
$mod = '-'.$timefrom['months'].' months';
$testnewer -> modify($mod);
$timefrom['days'] = $this->find_AllDaysFromThisTo($testnewer);
return $timefrom;
} // end function find_TimeFromThisTo
public function find_YearsFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 year');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 year');
}
return $count;
} // end function find_YearsFromThisTo
public function find_MonthsFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 month');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 month');
}
return $count;
} // end function find_MonthsFromThisTo
public function find_AllDaysFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 day');
while ( $this->format('U') < $testnewer->format('U')) {
$count ++;
$testnewer -> modify ('-1 day');
}
return $count;
} // end function find_AllDaysFromThisTo
public function find_WeekdaysFromThisTo($newer) {
/*
If the passed is:
not an object, not of class DateTime or one of its children,
or not larger (after) $this
return false
*/
if (!is_object($newer) || !($newer instanceof DateTime) || $newer->format('U') < $this->format('U'))
return FALSE;
$count = 0;
// Clone because we're using modify(), which will destroy the object that was passed in by reference
$testnewer = clone $newer;
$testnewer -> modify ('-1 day');
while ( $this->format('U') < $testnewer->format('U')) {
// If the calculated day is not Sunday or Saturday, count this day
if ($testnewer->format('w') != '0' && $testnewer->format('w') != '6')
$count ++;
$testnewer -> modify ('-1 day');
}
return $count;
} // end function find_WeekdaysFromThisTo
public function set_Day($newday) {
if (is_int($newday) && $newday > 0 && $newday < 32 && checkdate($this->format('m'),$newday,$this->format('Y')))
$this->setDate($this->format('Y'),$this->format('m'),$newday);
} // end function set_Day
public function set_Month($newmonth) {
if (is_int($newmonth) && $newmonth > 0 && $newmonth < 13)
$this->setDate($this->format('Y'),$newmonth,$this->format('d'));
} // end function set_Month
public function set_Year($newyear) {
if (is_int($newyear) && $newyear > 0)
$this->setDate($newyear,$this->format('m'),$this->format('d'));
} // end function set_Year
} // end class Extended_DateTime
В то время как для большинства операций даты и времени я обычно преобразовывал бы в Unixtime и выполнял бы дополнительное вычитание и т.д. на целом числе Unixtime, можно хотеть посмотреть на платформу Зенда класс Zend_Date.
Это имеет большую функциональность, которую Вы описываете. Хотя Пехлеви тарифицирован как "платформа", он работает исключительно хорошо библиотекой классов, чтобы привередливо выбрать элементы от. Мы обычно включаем его в проекты и затем просто вытягиваем в битах как и когда нам нужны они.
strtotime () полезен, но он действительно имеет некоторые нечетные поведения, которые могут время от времени раскрываться, если Вы только используете его для преобразования отформатированной даты / строка времени.
вещи как "+1 месяц" или "-3 дня" не могут иногда давать Вам, что Вы ожидаете, что это произведет.
PEAR::Date
похож на него, мог бы иметь некоторую полезную функциональность.
PEAR::Calendar
могло бы также быть полезным.
Можно использовать комбинацию strtotime, mktime и даты todo арифметика
Вот пример, который использует комбинацию todo некоторый арифметический http://rushi.wordpress.com/2008/04/13/php-print-out-age-of-date-in-words/, я воспроизведу код здесь для простоты
if ($timestamp_diff < (60*60*24*7)) {
echo floor($timestamp_diff/60/60/24)." Days";
} elseif ($timestamp_diff > (60*60*24*7*4)) {
echo floor($timestamp_diff/60/60/24/7)." Weeks";
} else {
$total_months = $months = floor($timestamp_diff/60/60/24/30);
if($months >= 12) {
$months = ($total_months % 12);
$years = ($total_months - $months)/12;
echo $years . " Years ";
}
if($months > 0)
echo $months . " Months";
}
?>
Самый легкий метод должен использовать метку времени, представляя число секунд с 1 января 2008. С типом метки времени можно сделать вещи как...
now = time();
tomorrow = now + 24 * 60 * 60; // 24 hours * 60 minutes * 60 seconds
Проверьте документацию в течение времени (), дата () и mktime () на php веб-страницах. Это - три метода, которые я склонен использовать наиболее часто.
@Rushi мне не нравится strtotime () лично.. я не знаю, почему, но я обнаружил этим утром, что, передавая строку как это '11.09.2008 9:5 AM' к strtotime возвращает false...
Я не думаю код, который Вы предоставили, решают проблему в качестве примера, 'Учитывая две даты, сколько рабочих дней там между этими двумя датами? Реализация или в SQL или в $pet_lang' и я не имею, рассматривают, есть ли у меня список государственного праздника...
Я настоятельно рекомендовал бы использовать PHP 5.2's объекты DateTime, вместо того, чтобы использовать метки времени UNIX, при выполнении вычислений даты. При использовании функций даты PHP, которые возвращают метки времени UNIX, у Вас есть очень ограниченный диапазон для работы с (например, ничто до 1970).
Можно получить количество дней между двумя датами как это:
$days = (strtotime("2008-09-10") - strtotime("2008-09-12")) / (60 * 60 * 24);
И можно сделать функцию чем-то как этот (у меня нет php установленным в моем рабочем компьютере, таким образом, я не могу гарантировать, что синтаксис на 100% правилен),
function isWorkDay($date)
{
// check if workday and return true if so
}
function numberOfWorkDays($startdate, $enddate)
{
$workdays = 0;
$tmp = strtotime($startdate);
$end = strtotime($enddate);
while($tmp <= $end)
{
if ( isWorkDay( date("Y-m-d",$tmp) ) ) $workdays++;
$tmp += 60*60*24;
}
return $workdays;
}
Если Вам не нравится strtotime, и у Вас всегда есть дата в том же формате, который можно использовать, взрывают функцию как
list($year, $month, day) = explode("-", $date);
Если Вы взглянете на http://php.net/date, то Вы найдете некоторые примеры использования mktime()
выполнить операции.
Простой пример был бы к тренировке, какова tomorrows дата будет. Можно сделать это путем простого добавления 1 к дневному значению в mktime()
следующим образом:
$tomorrow = date("Y-m-d", mktime(0, 0, 0, date("m"), date("d") + 1, date("Y")));
Таким образом, здесь, Вы получите дату в форме YYYY-MM-DD, содержащего tomorrows дата. Можно также вычесть дни путем простой замены '+' с '-'. mktime()
делает жизнь намного легче, и сохраняет Вас от необходимости сделать вложенный если операторы и другое такое неприятное кодирование.
]Для добавления даты можно использовать метод []DateTime::add[] ([]Добавляет количество дней, месяцев, лет, часов, минут и секунд к объекту DateTime[]), доступный с php 5. 3.0 и далее.[
] []Для нахождения разницы между двумя датами существует метод []DateTime::diff[]; но, похоже, нет метода подсчета рабочих дней между двумя датами.[
].