Echo text within time range - php

I have a script to display business hours for three days from today.
The script works fine, but now I want to display if we are currently open or closed.
If the current time is after the closing time OF TODAY ($openingsuur_vandaag[1]) I would like to display "CLOSED".
Let's start with the script:
<?php
$i = 0;
$periodes = array();
$periodes[$i]['start'] = '2020-01-01';
$periodes[$i]['stop'] = '2020-12-31';
$periodes[$i]['open'] = array(null,"10:00","09:00","09:00","09:00","09:00","10:00");
$periodes[$i]['dicht'] = array(null,"16:00","10:00","18:00","18:00","14:00","15:00");
$periodes[$i]['behalve'] = array();
$periodes[$i]['behalve'][0]['dag'] = "2020-06-01";
$periodes[$i]['behalve'][0]['open'] = null;
$periodes[$i]['behalve'][0]['dicht'] = null;
$i++;
echo getOpeningsuren(time(), $periodes);
function getOpeningsuren($date, $periodes)
{
$resultaat = '';
$a = date("d-m-Y");
$b = date("d-m-Y",strtotime('tomorrow'));
$c = date("d-m-Y",strtotime('tomorrow + 1 day'));
$m_nu = new datum();
$m_morgen = new datum();
$m_morgen->add(0,0,1);
$m_overmorgen = new datum();
$m_overmorgen->add(0,0,2);
$openingsuur_vandaag = getOpeningsuur($m_nu, $periodes);
$openingsuur_morgen = getOpeningsuur($m_morgen, $periodes);
$openingsuur_overmorgen = getOpeningsuur($m_overmorgen, $periodes);
$resultaat = $resultaat . $a. ' '. ($openingsuur_vandaag[0] == null ? 'gesloten' :
$openingsuur_vandaag[0].' - '. $openingsuur_vandaag[1].' uur') .'<br>';
$resultaat = $resultaat . $b. ' '. ($openingsuur_morgen[0] == null ? 'gesloten' :
$openingsuur_morgen[0].' - '. $openingsuur_morgen[1].' uur') .'<br>';
$resultaat = $resultaat . $c. ' '. ($openingsuur_overmorgen[0] == null ? 'gesloten' :
$openingsuur_overmorgen[0].' - '. $openingsuur_overmorgen[1].' uur') .'';
return $resultaat;
}
function getOpeningsuur($date, $periodes)
{
$periodestart = new datum();
$periodestop = new datum();
foreach ($periodes as $periode)
{
$periodestart->setDatetime($periode["start"] ." 00:00:00");
$periodestop->setDatetime($periode["stop"] ." 00:00:00");
if ($date->getTime() < $periodestart->getTime())
continue;
if ($date->getTime() > $periodestop->getTime())
continue;
foreach ($periode['behalve'] as $uitzondering)
{
if ($date->getDate() == $uitzondering['dag'])
{
return array($uitzondering['open'], $uitzondering['dicht'] );
}
}
return array($periode['open'][ $date->dag_vd_week() ], $periode['dicht'][ $date->dag_vd_week() ] );
}
return array(null, null);
}
class datum
{
function datum( $tijd=0 )
{
($tijd ? $tijd=$tijd : $tijd = time() );
$this->dagen_kort = array("zo", "ma", "di", "wo", "do", "vr", "za" );
$this->setTime( $tijd );
}
var $jaar;
var $maand;
var $dag;
var $uur;
var $minuut;
var $seconde;
var $dagen_kort;
function setTime( $time )
{
$this->jaar = date("Y", $time);
$this->maand = date("m", $time);
$this->dag = date("d", $time);
$this->uur = date("H", $time);
$this->minuut = date("i", $time);
$this->seconde = date("s", $time);
}
function getTime()
{
return mktime($this->uur, $this->minuut, $this->seconde, $this->maand, $this->dag, $this->jaar);
}
function setDatetime($datetime)
{
$dt = explode (" ", $datetime);
list($this->jaar, $this->maand, $this->dag) = explode("-", $dt[0]);
list($this->uur , $this->minuut, $this->seconde) = explode(":", $dt[1]);
}
function getDate()
{
return str_pad($this->jaar, 4, "0", STR_PAD_LEFT) .'-'. str_pad($this->maand, 2, "0", STR_PAD_LEFT)
.'-'. str_pad($this->dag, 2, "0", STR_PAD_LEFT);
}
function dag_vd_week()
{
return date("w", $this->getTime());
}
function setVars($jaar=-1, $maand=-1, $dag=-1, $uur=-1, $minuut=-1, $seconde=-1)
{
($jaar > -1 ? null : $this->jaar = $jaar);
($maand > -1 ? null : $this->jaar = $maand);
($dag > -1 ? null : $this->jaar = $dag);
($uur > -1 ? null : $this->jaar = $uur);
($minuut > -1 ? null : $this->jaar = $minuut);
($seconde > -1 ? null : $this->jaar = $seconde);
}
function add($jaar=0, $maand=0, $dag=0, $uur=0, $minuut=0, $seconde=0)
{
$nieuwe_tijd = mktime($this->uur + $uur, $this->minuut + $minuut, $this->seconde + $seconde, $this-
>maand + $maand, $this->dag + $dag, $this->jaar + $jaar);
$this->setTime($nieuwe_tijd);
}
}
?>
In the first place, my solution was, but does not work :-(:
$OFFICETIME = date("h:i"); // current time
if ($openingsuur_vandaag[1] > $OFFICETIME ) { // today's closing time - current time
echo "closed";
}
else{echo "open";}

Related

How to improve the loading of my PHP script for a calendar with different slots

I have a script that allows me to automatically generate slots on a calendar according to the different opening hours of my users.
Today, I would like to improve the execution of my script to make it much faster than today (it takes a few seconds to make the calendar appear).
You have to know that I have a table OPENING_TIMES which contains 7 rows (1 per day) for each user.
I tried some improvements but without success (with joins for example).
Do you have any ideas?
Thanks in advance !
$Sch_Link_User = $_GET['psy'];
$Data_query = mysqli_query($_Db_Con, 'SELECT ID_UNIQUE, CONSULTATION_TIME, CONSULTATION_TIME_BEFORE, TIMEZONE FROM USERS WHERE PROFILE_URL LIKE "' . $Sch_Link_User . '"');
$Data = mysqli_fetch_assoc($Data_query);
$Sch_Id_User = $Data['ID_UNIQUE'];
$Difference = '0';
switch ($Data['CONSULTATION_TIME']) {
case 1:
$Sch_Time_Consultation = 30;
break;
case 2:
$Sch_Time_Consultation = 45;
break;
case 3:
$Sch_Time_Consultation = 60;
break;
default:
$Sch_Time_Consultation = 60;
}
$Calendar = array();
$weekslots = array_map(function($dow) {return array('dow' => $dow, 'hour' => 00);}, range(0, 6));
$date = time();
$end_date = $date + (6 * 7 * 24 * 60 * 60);
$open_hours_cache = array();
while($date <= $end_date) {
$date_dow = date('w', $date);
foreach($weekslots as $timeslot) {
if($date_dow == $timeslot['dow']) {
$timeofday = $date + (3600 * $timeslot['hour']);
for($nd = 1; $nd <= 7; $nd++) {
if(date('N', $timeofday) == $nd) {
if (!isset($open_hours_cache[$nd])) {
$Data_Openhours_query = mysqli_query($_Db_Con, 'SELECT START_HOUR_M, END_HOUR_M, START_HOUR_A, END_HOUR_A FROM OPENING_TIMES WHERE ID_USER = "' . $Sch_Id_User . '" AND WEEKDAY = "' . $nd . '" AND CLOSED = 0');
$open_hours_cache[$nd] = mysqli_fetch_assoc($Data_Openhours_query);
}
$Data_Openhours = $open_hours_cache[$nd];
if(isset($Data_Openhours['START_HOUR_M']) && $Data_Openhours['END_HOUR_M'] == NULL && $Data_Openhours['START_HOUR_A'] == NULL && isset($Data_Openhours['END_HOUR_A'])) {
$shm = strtotime($Data_Openhours['START_HOUR_M'] . $Difference . ' hour');
$eha = strtotime($Data_Openhours['END_HOUR_A'] . $Difference . ' hour');
$timeslots = array();
$interval = new DateInterval("PT{$Sch_Time_Consultation}M");
$timeRange = new DatePeriod(new DateTime(date('Y-m-d H:i', $shm)), $interval, new DateTime(date('Y-m-d H:i', $eha)));
foreach ($timeRange as $time) {
$timeslots[] = $time->format("H:i");
}
foreach ($timeslots as $slot) {
$datefinal = date('Y-m-d', $timeofday) . ' ' . $slot . ':00';
$timestamp = strtotime($datefinal . $Difference . ' hour');
$Check_Slot = mysqli_query($_Db_Con, 'SELECT ID, ID_USER, STATUS FROM APPOINTMENTS WHERE ID_USER = "' . $Sch_Id_User . '" AND DATE_START = "' . $timestamp . '" AND (STATUS = 1 OR STATUS = 2 OR STATUS = 9 OR STATUS = 10) AND DATE_START > "' . $Time . '"');
$Data_Slot = mysqli_fetch_assoc($Check_Slot);
$status = isset($Data_Slot['STATUS']) && $Data_Slot['STATUS'] == 9 && $Data_Slot['ID_USER'] == $_SESSION['uid'];
$check_slot = mysqli_num_rows($Check_Slot) == 0;
$time_before = ($Time + (60 * 60 * $Data['CONSULTATION_TIME_BEFORE'])) < $timestamp;
if ($status) {
$class = 'blocked';
} elseif ($check_slot && $time_before) {
$class = 'available';
} else {
$class = 'unavailable';
}
$Calendar[] = array(
'id' => date('Y-m-d', $timeofday) . '/' . $slot,
'title' => $slot,
'class' => $class,
'psy' => $Sch_Id_User,
'start' => $timestamp . '000',
);
}
} else if(isset($Data_Openhours['START_HOUR_M']) && isset($Data_Openhours['END_HOUR_M']) && isset($Data_Openhours['START_HOUR_A']) && isset($Data_Openhours['END_HOUR_A'])) {
$shm = strtotime($Data_Openhours['START_HOUR_M'] . $Difference . ' hour');
$ehm = strtotime($Data_Openhours['END_HOUR_M'] . $Difference . ' hour');
$sha = strtotime($Data_Openhours['START_HOUR_A'] . $Difference . ' hour');
$eha = strtotime($Data_Openhours['END_HOUR_A'] . $Difference . ' hour');
$timeslots = array();
$interval = new DateInterval("PT{$Sch_Time_Consultation}M");
$timeRange = new DatePeriod(new DateTime(date('Y-m-d H:i', $shm)), $interval, new DateTime(date('Y-m-d H:i', $ehm)));
foreach ($timeRange as $time) {
$timeslots[] = $time->format("H:i");
}
$timeRange = new DatePeriod(new DateTime(date('Y-m-d H:i', $sha)), $interval, new DateTime(date('Y-m-d H:i', $eha)));
foreach ($timeRange as $time) {
$timeslots[] = $time->format("H:i");
}
foreach ($timeslots as $slot) {
$datefinal = date('Y-m-d', $timeofday) . ' ' . $slot . ':00';
$Check_Slot = mysqli_query($_Db_Con, 'SELECT ID, ID_USER, STATUS FROM APPOINTMENTS WHERE ID_USER = "' . $Sch_Id_User . '" AND DATE_START = "' . strtotime($datefinal) . '" AND (STATUS = 1 OR STATUS = 2 OR STATUS = 9 OR STATUS = 10) AND DATE_START > "' . $Time . '"');
$Data_Slot = mysqli_fetch_assoc($Check_Slot);
// * 24 le temps avant possibilité de prende rendez-vous
$status = isset($Data_Slot['STATUS']) && $Data_Slot['STATUS'] == 9 && $Data_Slot['ID_USER'] == $_SESSION['uid'];
$check_slot = mysqli_num_rows($Check_Slot) == 0;
$time_before = ($Time + (60 * 60 * $Data['CONSULTATION_TIME_BEFORE'])) < strtotime($datefinal . $Difference . ' hour');
if ($status) {
$class = 'blocked';
} elseif ($check_slot && $time_before) {
$class = 'available';
} else {
$class = 'unavailable';
}
$Calendar[] = array(
'id' => date('Y-m-d', $timeofday) . '/' . $slot,
'title' => $slot,
'class' => $class,
'psy' => $Sch_Id_User,
'start' => strtotime($datefinal . $Difference . ' hour') . '000',
);
}
}
}
}
}
}
$date += 86400;
}
$Calendar_Data = array(
'success' => 1,
'result' => $Calendar);
echo json_encode($Calendar_Data);
So I try to have a much faster loading with joins or a cache system to limit the number of requests.
Moreover, wouldn't it be more efficient if I also put everything in one column of my user table, the schedules?

PHP - ask user input for dates and pass to script

I have a php script here to create login at our datacenter for myself, but this script is doing the login for next week if i run it after 12:00 on monday, and a lot of times I'm not there the whole week, so I want to improve this script by asking for user input and pass the dates that I will be there so the script only picks up on those dates. I know i have to do this with stdin and I do have a part that works, but i have no idea on how to integrate this into the current script and how to make sure i can give multiple dates
My stdin part that does ask my for a date, but no idea on how to combine it:
<?php
function promptDateFromUser(string $prompt, string $dateFormat): DateTimeInterface
{
echo "{$prompt} [$dateFormat]: ";
$stdin = fopen('php://stdin', 'r');
$line = trim(fgets(STDIN));
fclose($stdin);
$dateTime = DateTimeImmutable::createFromFormat('Y-m-d', $line);
if (! $dateTime instanceof DateTimeInterface) {
throw new UnexpectedValueException('Invalid datetime format');
}
}
$dateTime = promptDateFromUser("Please insert date:", 'Y-m-d');
?>
My login script as of now:
<?php
require 'shared.php';
restore_exception_handler();
restore_error_handler();
$md = new RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$date = new DateTime();
$hour = (int)$date->format('H');
$dow = (int)$date->format('w');
if (($dow === 1 && $hour > 12) || ($dow > 1 && $dow < 6)) {
$add = 'P' . (8 - $dow) . 'D';
$date->add(new DateInterval($add));
}
if (($dow === 1 && $hour <= 12) || $dow === 0 || $dow === 6) {
if ($dow === 6) {
$date->add(new DateInterval('P2D'));
} elseif ($dow === 0 ) {
$date->add(new DateInterval('P1D'));
}
}
$tomorrow = $date->format('Y-m-d');
$duration = 720;
$customerId = 30;
$purpose = 'DCG visit';
$phoneNumber = '';
$name = 'SOME NAME, REMOVED FOR PUBLICATION';
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
for ($x = 0; $x < 5; $x++) {
$start = $tomorrow." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested for: ", $tomorrow, PHP_EOL;
$date->add(new DateInterval('P1D'));
$tomorrow = $date->format('Y-m-d');
}
?>
I'm a big php noob, so some explanation is greatly appreciated!
after some help from a friend, i managed to solve this:
#!/usr/bin/env php
<?php
include('shared.php');
restore_exception_handler();
restore_error_handler();
// Constants
$timeout = 45;
$md = new \RevisionModificationData;
$md->comment = 'Set by the dcgaccess script';
$duration = "720";
$customerId = "30";
$purpose = "DCG visit";
$phoneNumber = "";
$name="SOME NAME, REMOVED FOR PUBLICATION";
// Functions
function requestInput($msg) {
global $timeout;
echo "$msg\n\nThe timeout for this selection is $timeout seconds.\n\n> ";
$fd = fopen('php://stdin', 'r');
$read = array($fd);
$write = $except = array(); // we don't care about this
if(stream_select($read, $write, $except, $timeout)) {
$choice = trim(fgets($fd));
}
echo "\nYou typed: $choice\n\n";
return $choice;
}
// Start of program
$date = new DateTime();
$weekchoice = (int)requestInput("Which week would you like to request access for?\n1) Current week\n2) Next week\n3) Specific week number");
if ($weekchoice == 3) {
$weeknumber = (int)requestInput("Please enter a numeric week number");
} else {
$weeknumber = (int)$date->format("W");
if ($weekchoice == 2) {
$weeknumber += 1;
}
}
// We override $date with the start of the chosen week
$date->setISODate($date->format("Y"), $weeknumber);
echo "Thanks, you chose week $weeknumber which starts with " . $date->format("l d F, Y") . " \n\n";
$dayschoice = requestInput("Please enter the days you want access, as a space separated list:\n1) Monday\n2) Tuesday\n3) Wednesday\n4) Thursday\n5) Friday\n\nExample: 1 3 5");
$daylist = explode(' ', $dayschoice);
$processedDays = [];
foreach ($daylist as $eachday) {
$iday = (int)$eachday;
if ($iday == 0 || $iday % 7 == 0) { // No Sundays, also (int)"" -> 0, which is terrible
continue;
}
$add_days = $iday - 1; // Sums 0 if Monday, 1 if Tuesday and so on...
$newdate = new DateTime($date->format("Y-m-d"));
$newdate->modify("+$add_days days");
$processedDays[] = $newdate;
$formatted = $newdate->format("l d F Y");
echo "Processing day $iday, which is $formatted\n";
}
$hour = $date->format('H');
$tomorrow = $date->format('Y-m-d');
$confirm = requestInput("\nRequest access for these days? Yes/No");
if ($confirm != "Yes") {
echo 'Good bye!';
exit(0);
}
foreach ($processedDays as $reqDay) {
echo "Submitting " . $reqDay->format("l d F Y") . "\n";
$colo = Colo::getByName($name);
Ensure::notNull($colo, "Colo for RackSpace is null when it should not be!");
$spaces = $colo->getRackSpaces();
foreach ($spaces as $space) {
$rackSpace = $space;
}
Ensure::notNull($rackSpace, "RackSpace is null when it should not be!");
if ($colo->getCustomerId() != $customerId) {
throw new UserException(ErrorCodes::PERMISSION_DENIED);
}
}
foreach ($processedDays as $reqDay) {
$start = $reqDay->format('Y-m-d')." 8:00:00";
$end = Util::stringToMysqlDateTime($start . ' + ' . $duration . ' minutes');
$shouldSms = strlen((string)$phoneNumber) > 0;
$req = BioAccessRequest::create($rackSpace, $purpose, $start, $end, $shouldSms, $md);
$users = BioAccessUser::getAll();
foreach ($users as $user) {
if ($user->name === 'USER NAME') {
$req->addBioAccessUser($user, $md);
}
}
$req->request();
echo "Access requested: ", $reqDay->format('l d F Y'), PHP_EOL;
$tomorrow = $date->format('Y-m-d');
}
?>

Date Array For Every Day, Week, Month, Year in between 2 dates

I am trying to create an array using PHP OOP that basically creates and array for every day, month, year within 2 dates and allocates a ticket and hours worked set at 0 for every single day that has passed.
The code I have used is:
class statisticsClass{
private $DateFrom = null;
private $DateTo = null;
private $startYear = null;
private $startMonth = null;
private $startDay = null;
private $endYear = null;
private $endMonth = null;
private $endDay = null;
private $theDateDif = null;
private $stages = null;
private function makeDates(){
if(!empty($this->DateFrom)){
$this->DateFrom = $this->generals->convertDate($this->DateFrom);
} else {
$this->DateFrom = date('Y-m-d', strtotime('last year')) . ' 00:00:00';
}
if(!empty($this->DateTo)){
$this->DateTo = $this->generals->convertDate($this->DateTo);
} else {
$this->DateTo = date('Y-m-d', strtotime('now')) . ' 23:59:59';
}
list($theDate, $theTime) = explode(' ', $this->DateFrom);
list($this->startYear, $this->startMonth, $this->startDay) = explode('-', $theDate);
list($theDate2, $theTime2) = explode(' ', $this->DateTo);
list($this->endYear, $this->endMonth, $this->endDay) = explode('-', $theDate2);
}
private function removeZeros($number){
return ltrim($number, '0');
}
private function chartItemVersion(){
if($this->theDateDif <= 31){
$this->stages = 'daily';
} elseif($this->theDateDif > 31 && $this->theDateDif <= 183){
$this->stages = 'weekly';
} else {
$this->stages = 'monthly';
}
}
private function addZeros($number){
if($number < 10){
return '0' . $number;
}
return $number;
}
private function makingQueryArray(){
for($yearMake=$this->startYear; $yearMake<=$this->endYear; $yearMake++){
$this->queryArray[] = intval($yearMake);
}
foreach($this->queryArray as $year){
if($year === $this->startYear){
$currentMonth = intval($this->removeZeros($this->startMonth));
for($currentMonth; $currentMonth <= 12;$currentMonth++){
$this->queryArray[$year][] = (string)$this->addZeros($currentMonth);
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($currentMonth), $year);
if($this->startYear === $this->addZeros($currentMonth)){
$currentDay = intval($this->removeZeros($this->startDay));
for($currentDay; $currentDay <= $tempHowManyDays; $currentDay){
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($currentDay)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($currentDay)]['Hours'] = 0;
}
} else {
for($i=1; $i<=$tempHowManyDays; $i++){
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($i)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($i)]['Hours'] = 0;
}
}
}
} elseif($year === $this->endYear) {
$endMonth = intval($this->removeZeros($this->endMonth));
for($a=1; $a <= $endMonth; $a++){
$this->queryArray[$year][] = (string)$this->addZeros($a);
if($a === $endMonth){
$tempHowManyDays = intval($this->removeZeros($this->endDay));
} else {
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($a), $year);
}
for($b=1; $b<=$tempHowManyDays; $b++){
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['Hours'] = 0;
}
}
} else {
for($a=1; $a <= 12; $a++){
$this->queryArray[$year][] = (string)$this->addZeros($a);
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($a), $year);
for($b=1; $b<=$tempHowManyDays; $b++){
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['Hours'] = 0;
}
}
}
}
var_dump($this->queryArray);
}
private function dateDifference(){
$now = strtotime($this->DateFrom);
$your_date = strtotime($this->DateTo);
$datediff = $your_date - $now;
$this->theDateDif = round($datediff / (60 * 60 * 24));
}
function __construct($pdo, $theArray, $generals = null){
if($generals !== null){ $this->generals = $generals; }
$this->pdo = $pdo;
if(isset($theArray['DateFrom']) && !empty($theArray['DateFrom'])){ $this->DateFrom = $theArray['DateFrom']; }
if(isset($theArray['DateTo']) && !empty($theArray['DateTo'])){ $this->DateTo = $theArray['DateTo']; }
$this->makeDates();
$this->dateDifference();
$this->chartItemVersion();
$this->makingQueryArray();
var_dump($this->queryArray);
}
}
$theArray = array();
$amhStatistics = new statisticsClass($pdo, $theArray, $generals);
I have been playing around with it for a while and can not get this array to function corectly.
The array should look like this:
array(){
'2018' => array(
01 => array(
01 => array(
'ticket' => 0,
'hours' => 0,
),
02 => array(
'ticket' => 0,
'hours' => 0,
)
)
)
}
As stated the only stipulation is that the start date should start at the start date and the end date should start at the end date.
Could someone point me in the right direction.
Cheers.
Your makingQueryArray function seems complicate - I believe you should solve it differently.
You can use dateperiod to get all days between 2 dates:
$startDate = '2010-10-01';
$endDate = '2010-10-05';
$period = new DatePeriod(new DateTime($startDate), new DateInterval('P1D'), new DateTime($endDate));
Now You can loop on all days and set you array:
foreach ($period as $key => $value) {
$d = explode("-", $value->format('Y-m-d'));
$res[$d[0]][$d[1]][$d[2]] = array('ticket' => 0, 'hours' => 0);
}
$res will give you your desire output. Live example: 3v4l

Php datetime function doesn't recognise dates before 1000

This code is used to take values inputted from a form but this does not take a year entered as 0100 as 0100 but as 1915, this is then used with the JS seen in one of my other questions any help here would be very good, I think the issue is something to do where the year is taken but I just can't get this to work correctly. Is this a limitation of php?
<?php
$year = "";
$month = "";
$day = "";
if (isset($_GET['year']) && !empty($_GET['year'])) {
$year = $_GET['year'];
}
if (isset($_GET['month']) && !empty($_GET['month'])) {
$month = $_GET['month'];
$monthNumber = date('m', strtotime("$month 1 Y"));
}
if (isset($_GET['day']) && !empty($_GET['day'])) {
$day = $_GET['day'];
}
if ($year != "" && $monthNumber != "" && $day != "") {
$fullUrlDate = $year . "-" . $monthNumber . "-" . $day;
$urlDate = new DateTime(date($fullUrlDate));
$today = new DateTime(date("Y-m-d H:i:s"));
$interval = $urlDate->diff($today);
$gapYears = $interval->y;
$gapMonths = $interval->m;
$gapDays = $interval->d;
$gapDaysTotal = $interval->days;
$gapWeeksTotal = round($interval->days/7);
$gapHours = $interval->h;
$gapMinutes = $interval->i;
$gapSeconds = $interval->s;
if ($gapWeeksTotal == 1) {
$gapWeeksSuffix = "";
} else {
$gapWeeksSuffix = "s";
}
if ($gapDays == 1) {
$gapDaysSuffix = "";
} else {
$gapDaysSuffix = "s";
}
$ordinalSuffix = date("S", strtotime($fullUrlDate));
if (strtotime($fullUrlDate) < strtotime(date("Y-m-d H:i:s")) ) {
$dateInThePast = true;
} else {
$dateInThePast = false;
}
// Months gap
$monthsInterval = date_diff($urlDate, $today);
$monthsGap = $monthsInterval->m + ($monthsInterval->y * 12);
$gapMonthsSuffix = ($monthsGap == 1 ? "" : "s");
DateTime has no such limitation, but the date function you use to initialise it, does. You can use DateTime::setDate to set any year you want:
php > $a = new DateTime("2015-08-24");
php > echo $a->format(DateTime::ISO8601);
2015-08-24T00:00:00+0000
php > $a->setDate(90, 8, 24);
php > echo $a->format(DateTime::ISO8601);
0090-08-24T00:00:00+0000
php > $a->setDate(90090, 8, 24);
php > echo $a->format(DateTime::ISO8601);
90090-08-24T00:00:00+0000

Wrong output on date

if(isset($_POST['submit_event'])){
$m = $_POST['event_month'];
$y = $_POST['event_year'];
$d = $_POST['event_day'];
$date = date('Y-n-d',strtotime($y. '-' .$m. '-' .$d));
echo $date;
//i always get 2013-10-07
}
All my inputted datas are correct although the output is always wrong and the same.
if (isset($_POST['submit_event']) && isset($_POST['event_month']) && isset($_POST['event_year']) && isset($_POST['event_day'])) {
$m = $_POST['event_month'];
$y = $_POST['event_year'];
$d = $_POST['event_day'];
$date_pre = $y. '-' .$m. '-' .$d;
$time = strtotime($date_pre)
$date = date('Y-n-d', $time);
echo $date;
}
// For debugging:
else {
echo "Not all variables have been set."
}

Categories