简体   繁体   中英

PHP total the number of days taken as leave within a yearly period

Am struggling about how to go about implementing this. I am fairly new with this language so any help would be greatly appreciated.

I have developed functionality whereby users are able to log annual leave, by selcting date to and date from etc. What I'd like to be able to do is be able to display how much leave is remaining / set a limit on logging leave they go over the 25 day limit within the yearly leave period.

I have looked at various php functions like date interval and date time, but can't figure out how I would use them.

I would do something like this to tally up the total days taken.

<?php
$time_off_requests = array(0 => array('start_date' => '2015-01-01', 'end_date' => '2015-01-14'), array('start_date' => '2015-12-20', 'end_date' => '2016-01-02');
$total_days = 0;
foreach($time_off_requests as $time_out) {
    $datetime1 = new DateTime($time_out['start_date']);
    $datetime2 = new DateTime($time_out['end_date']);
    $interval = $datetime1->diff($datetime2);
    $total_days += (int)$interval->format('%a');
}
echo 'Out for a total of '.$total_days.' days this period.';

However if your data is in a MySQL database I would suggest doing that in the SQL Query unless you have a good reason not to.

   $maxHolidays = 25;
   $holidaysTaken = 0; //populate this from a database, Past holidays
   $start = new DateTime('2015-07-26');
   $end  = new DateTime('2015-08-26');
   $diff = $dStart->diff($dEnd);

   if ($holidaysTaken + $diff < $maxHolidays) {
     // Add the holiday
     //add to the database
   } else {
     //reject the holiday
   }

Something like that should work,

In reality though half day holidays are possible

You will likely have to check for holidays crossing years etc also depending on requirements

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM