Need help with php.
So I am writing this for a shop. This function returns false whenever they are closed (opening at 9:30 and closing at 22:45).
I need it to ALSO return false when the current day of the week is Saturday or Sunday.
Here is the function:
function can_order_now_timeframe(){
$morning= new DateTime("09:30", new DateTimeZone('Europe/Budapest'));
$night = new DateTime("22:45", new DateTimeZone('Europe/Budapest'));
$morning_u = $morning->format('U');
$night_u = $night->format('U');
$datenow = new DateTime("now", new DateTimeZone('Europe/Budapest'));
$timestampnow = $datenow->format('U');
if(($morning_u<$timestampnow) && ($timestampnow < $night_u)){
return true;
}else{
return false;
}
}
Thanks for the help.
Using the date object (credits to Icecub)
function isWeekend($datenow){
$day = $datenow->format('%w');
if ($day=="0"||$day=="6"){
return true;
}else{
return false;
}
}
Using date and strtotime in combination with the timestamp ($timestampnow)
If you have PHP >= 5.1:
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
otherwise:
function isWeekend($date) {
$weekDay = date('w', strtotime($date));
return ($weekDay == 0 || $weekDay == 6);
}
A complete code would look like ths. (You can use a function inside a function)
<?php
function isWeekend($datenow){
$day = $datenow->format('%w');
if ($day=="0"||$day=="6"){
return true;
}else{
return false;
}
}
function can_order_now_timeframe(){
$morning= new DateTime("09:30", new DateTimeZone('Europe/Budapest'));
$night = new DateTime("22:45", new DateTimeZone('Europe/Budapest'));
$morning_u = $morning->format('U');
$night_u = $night->format('U');
$datenow = new DateTime("now", new DateTimeZone('Europe/Budapest'));
$timestampnow = $datenow->format('U');
if(($morning_u<$timestampnow) && ($timestampnow < $night_u) && !isWeekend($datenow)){
return true;
}else{
return false;
}
}
?>
or you can have it all inside one function like this if you dont think you might need the weekend detection again:
<?php
function can_order_now_timeframe(){
$morning= new DateTime("09:30", new DateTimeZone('Europe/Budapest'));
$night = new DateTime("22:45", new DateTimeZone('Europe/Budapest'));
$morning_u = $morning->format('U');
$night_u = $night->format('U');
$datenow = new DateTime("now", new DateTimeZone('Europe/Budapest'));
$timestampnow = $datenow->format('U');
$day = $datenow->format('%w');
if ($day!="0" and $day!="6"){
if(($morning_u<$timestampnow) && ($timestampnow < $night_u)){
return true;
}else{
return false;
}
}else{
return false;
}
}
?>