亲爱的比我好的编码员,
我正在构建一个“小”脚本,它提供了以下信息:
我打破了这个问题,因为我可能会以非常低效的方式用很多if和其他来写这个。但我想学习。谁想帮忙?到目前为止我所拥有的(此代码可以工作,并给出了所选年份的总小时数):
$totalhours = 0;
//selected year var
$sel_year = 2017;
$prev_year = $sel_year -1;
$cur_year = date('Y', time());
$next_year = $sel_year +1;
// loop through all calendar data (.ics data)
foreach ($events as $event) {
// Start and end unixtimestamp of calendar item.
$dtstart = $ical->iCalDateToUnixTimestamp($event['DTSTART']);
$dtend = $ical->iCalDateToUnixTimestamp($event['DTEND']);
//which year the calendar items starts and end
$startevent_year = date('Y', $dtstart);
$endevent_year = date('Y', $dtstart);
//Calculates total hours of calendar item in this loop
$seconds = $dtend - $dtstart;
$hours = $seconds/3600;
//Add to total if item is in selected year
if(($startevent_year == $sel_year) && ($endevent_year == $sel_year)){
$totalhours += $hours;
}
}
答案 0 :(得分:2)
使用DateInterval
更容易:
$d1 = new DateTime('2017-01-01 10:00:00');
$d2 = new DateTime('2017-01-02 12:00:00');
$diff = $d2->diff($d1);
$hours = $diff->days * 24 + $diff->h;
echo $hours; // 26