So if it’s Sun through Sat between $due and $now, You’d want it to be 5 * $cost?
I would simply iterate from $now till $due, and use date() to check if it’s a saturday/sunday and skip it.
You could also do it mathematically based on the day $now is versus the day $due is, using modulus and some if condition checks, but I would just go with the first suggestion to make it easier on yourself and future maintainability.
Thank you for quick response.I’m not sure if I get it.
Assuming that I borrowed books from our library, and should be returned
after 6 days (excluding sat and sun), beyond that I must pay book fines with $1/day.
What do you mean by 5 * cost. ?
Hope I’m making my statement clear.
Thank you for the code, but can you explain or just tell something about your code? I’m new in php.
Where can I put my formula in finding the product of fines?
like now-due date = fines. How about the interval of book when borrowed? like when I borrowed book that should be returned after 3 days.
@wonshikee; You applied a very elegant solution to this problem. I have been away from PHP for a while and was struggling (mentally) between the two different approaches I would have taken.
Your code is concise, clean and effective!
:applause:
$query = mysql_query("SELECT * FROM tbl_studentbook WHERE id = 3") or die (mysql_error());
while ($row = mysql_fetch_array($query))
{
$bor = date_create($row['sbook_Borrow']);
$bor= date_format($bor,'N'); //2012-03-03 sat
$due = date_create($row['sbook_Due']);
$due= date_format($due,'N'); //2012-03-18 sun
$cost = 5;
if ($due == 6){
$due = $due + 2;
}if ($due == 7){
$due = $due + 1;}
//my new due date should be 2012-03-19 monday
$now = date();//assuming today is 2012-03-21 wed
//so I must pay 2 days book fines which cost $1
$fines = $now - $due;
$fines = 2 * $cost;
$totalfines = 10;
}
Here’s a little function that takes the due date and current date, and (should) return the number of days overdue.
function days_overdue(DateTime $due, DateTime $now)
{
// Skip to next weekday if on weekend
if (in_array($due->format('D'), array('Sat', 'Sun'))) {
$due = clone $due;
$due->modify('next weekday');
}
// Generate period of weekdays between start and end
$period = new DatePeriod($due, DateInterval::createFromDateString('next weekday'), $now, DatePeriod::EXCLUDE_START_DATE);
return iterator_count($period);
}
Your code snippet would then look like
while ($row = mysql_fetch_array($query))
{
// ...
$due = date_create($row['sbook_Due']);
$now = date_create();
$overdue = days_overdue($due, date_create());
// so I must pay $overdue days book fines which cost $cost dollars per day
$cost = 5;
$fines = $overdue_days * $cost;
// ...
}