I want to not include the penalties from Sunday , only Monday - Saturday only using this borrowdate,returndate, and currentdate Thankyou!

$borrowdate = new Datetime($row['date_return']);
$returndate = new Datetime($row['due_date']); 
$currentdate = new Datetime();        
$fines = 0;
if($currentdate > $returndate){
     $days = $borrowdate->diff($returndate ?? $currentdate, true)->days;
     echo "₱ ". $fines = $days > 0 ? intval(floor($days)) * 15 : 0;
     $fi = $row['borrow_details_id'];
     mysqli_query($dbcon,"update borrowdetails set fines='$fines' where borrow_details_id = '$fi'");
}

Recommended Answers

All 3 Replies

Member Avatar for diafol

Here's an example of why you should use a straight calculation rather than a loop (as suggested by others in various forums) - the array function should slow it down nicely too! In my simple tests, the calculation was around 10x faster:

<?php
//DIY - loopy fun! Using 'w' - 0 = Sunday and 1 = Monday
function wFines( $dateDue, $dateReturn = 'today', $notCountDaysWArray=[0,1] )
{
    $due = new DateTime($dateDue);

    $ret = new DateTime($dateReturn);
    $days = $due->diff($ret)->days;
    if($days < 1) return 0;
    $arr = [];
    $i = $due->format('w');
    for($d=0;$d<$days;$d++){
        $arr[] = $i;
        $i++;
        if($i==7)$i=0;
    }
    $r = array_diff($arr, $notCountDaysWArray);
    return count($r);
}

//based on https://stackoverflow.com/a/15887105/4629068
//Using 'N' - 7 = Sunday, 1 = Monday
function nFines( $dateDue, $dateReturn= 'today', $notCountDaysNArray = [7,1] )
{
    $start = new DateTime($dateDue);
    $end = new DateTime($dateReturn);
    $days = $start->diff($end)->days;
    $off = 0;
    foreach ($notCountDaysNArray as $i) {
        $off += intval($days / 7) + ($start->format('N') + $days % 7 >= $i);
    }
    return $days - $off;
}

$start = microtime(true);
echo 'Days overdue = '.wFines('2017-08-23', '2022-08-23');
echo "<br />Time:" . (microtime(true) - $start);

$start = microtime(true);
echo 'Days overdue = '.nFines('2017-08-23', '2022-08-23');
echo "<br />Time:" . (microtime(true) - $start);

Using nFines function 10x faster than wFines.
BTW - if you will never need an array of days to ignore - just Sunday, you can use integers in params and change the code accordingly.

commented: Great solutions! :) +15
commented: Never on a Sunday. +12
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.