Insert weekly info from date and time php - php

I have a function that is accepting the date and time, and number of occurrences of an episode. I'm using a while loop to try and insert and episode every week on the same day and time. For example if the episode is monday at 7PM, i want to insert in for every monday at 7PM for the number of occurrences given.
Here's my code and while loop:
$sEpsAirDate = strtotime($aVars['air_date'].' '.$aVars['air_time'].$aVars['air_ampm']);
$i = 1;
while ($i <= $aVars['repeat_count']) {
$sEpsAirDate = // How can I alter this variable to change the date to every week?
db_res(
"INSERT INTO `hm_episodes_main` SET
`show_id` = '{$aVars['show_id']}',
`title` = '{$sEpsTitle}.{$i}',
`season` = '{$aVars['eps_season']}',
`uri` = '{$sUri}.{$i}',
`desc` = '{$sEpsDesc}',
`air_date` = '{$sEpsAirDate}'
");
$i++
}
How would I alter the $sEpsAirDate variable to be entered accurately on every day of the week on the given time?

Use mktime():
$next_ep_timestamp = mktime ($hour,$min,$sec, $first_ep_month, $first_ep_day + 7 * $weekcount, $first_ep_year);
"Init" this by setting the respective variables for the date, month and year of the first episode, then you can create new dates for following weeks by adding increments of 7 to the day-parameter in mktime (like shown above).
Then format for output to SQL like this:
$datetime_str = date("Y-m-d H:i:s", $next_ep_timestamp);
//gives a date-str like '2011-10-16 12:59:01'

The first idea that comes to my mind is just adding the seconds in a week to the sEpsAirDate with every iteration in the loop:
$sEpsAirDate += 604800;
If you needed to preserve the first air date you could copy it out into a separate variable and then do something like this (change the LCV $i to start at 0):
$sEpsAirDate = $sEpsFirstAirDate+(604800*$i);
But this method has the potential to create problems with Daylight Savings Time... so it might be safer to break the date into year, month and day variables and then recreate the $sEpsAirDate with every loop iteration by adding ($i*7) to day. ... So something like (again change the LCV $i to start at 0):
$sEpsAirDate = mktime($sEpsAirDateHour, $sEpsAirDateMinute, 0, $sEpsAirDateMonth, $sEpsAirDateDay+($i*7), $sEpsAirDateYear);

Related

PHP: How calculate calendar days with all 42 days

The goal is exclusively to get a range of days, in other words
, start date and end date, as if it were a "calendar matrix", containing the 42 days, being the days of the current month, with the days of the previous month and next month. No need to present (render) a calendar, only get dates.
For example, follow image below.
I need to enter a certain month of a given year, and would need to get this range of days, as picture.
Using PHP Carbon, I easily get the days of the current month, using startOfMonth(), endOfMonth() , subMonth(), addMonth().
Doing this, I get every day of these 3 months, but the goal is to be able to "filter" these days to present only the interval equal to a calendar, but obviously something dynamic, ie, if I use Carbon, would simply inform the desired date , and get "filtered" range, respecting the position of each "cell".
$prev_start = Carbon::now()->subMonth()->startOfMonth();
$prev_end = Carbon::now()->subMonth()->endOfMonth();
$start = Carbon::now()->startOfMonth();
$end = Carbon::now()->endOfMonth();
$next_start = Carbon::now()->addMonth()->startOfMonth();
$next_end = Carbon::now()->addMonth()->endOfMonth();
So here's what you can do:
$monthStart = Carbon::now()->startOfMonth();
$monthEnd = Carbon::now()->endOfMonth();
$calendarStart = $monthStart->startOfWeek(Carbon::SUNDAY);
$calendarEnd = $monthEnd->endOfWeek(Carbon::SATURDAY);
$calendarStart and $calendarEnd should now contain the first and last day that will be displayed in a single screen. This assumes that the calendar will expand the first and last week displayed.
If you are using a calendar that always shows 42 days regardless you can just do:
$monthStart = Carbon::now()->startOfMonth();
$calendarStart = $monthStart->startOfWeek(Carbon::SUNDAY);
$calendarEnd = $calendarStart->addDay(42);

Get number of occurrences/times between two dates

I'm trying to get the number of times between two dates. I'm provided with 4 types of info: freq, interval, startDate, and endDate.
For example:
freq = weekly
interval = 1
startDate = 2019-03-10
endDate = 2019-03-24
I'm trying to get the number of times/dates/events are between those two dates with the given info. (The count or the number of events)
In this example, since the frequency is weekly and the interval is 1, it means repeat the event on the startDate every 1 week. If the interval was changed to 2, it would be every 2 weeks. If the frequency was changed to daily, and the interval was 3, it would be every 3 days.
In this example, the first event would be on 2019-03-10 and then the second event would be on 2019-03-17, and then the third would be on 2019-03-24. The count is 3 in this example because there are three dates.
I am trying to find the count.
Thanks
Well, if you use Datetime class or Carbon, you can easily loop through the days/weeks/months between those dates. For example, if your freq = weekly and interval = 1, given the startDate and endDate you provided, the code would be something like this:
use Carbon\Carbon;
$startDate = Carbon::create(2019,03,10,0,0);
$endDate = Carbon::create(2019,03,24,0,0);
$count = 0;
while(! $startDate->greaterThan($endDate) )
{
$count += 1;
if($freq === 'weekly')
{
$startDate->addWeeks($interval);
}
else if($freq === 'monthly')
{
$stardDate->addMonths($interval);
}
}
In this example i've made using carbon because it saves you a lot of time, but you could do this by using PHP Datetime Class.

Compare difference between two dates PHP

I am trying to compare to date to figure out how much time is between them, which I know how to do, date_diff(), but I want to then compare the time between the dates and if it is greater than 7 days do something and if not do something else. I think it sounds easy and I know there are probably fairly simple solutions to do so but I am just not a fan of dates and comparisons. Here is a snippet of what I got so far as it is just one case of a switch statement so the rest are basically identical.
$array = array();
$today = date("Y-m-d"); // get today's date
foreach($arrayOfObjs as $obj){
if ($obj->get("renewalDate") >= $today){
array_push($array, $obj->get("renewalDate"));
}else{
switch($obj->get("recurrencePeriod")){
case 1:
/*
* All cases follow same structure
* Build the date in format Y-m-d from renewalDate out of the obj.
* Loop through the date while it's less than today.
* After date is greater than today return date add to array
*/
$date = DateTime::createFromFormat("Y-m-d", $obj->get('renewalDate'));
while($date <= $today){
$date->add(new DateInterval('P7D'));
}
$diff = date_diff($today, $date);
if($diff->format('%a') <= 7){
$obj->renewalDate($date);
array_push($array, $obj);
}
break;
Basically, my database stores dates and those dates could be passed but it could be a reoccurring event. To calculate the next time that event would happen I check if the data in the database is before today's date and if it is then I continue to add the incremental amount (in this case 7 for a weekly reoccurring event) and compare the dates again. After the date that is incremented passes today's date I want to find out if it is within 7 days and if so add it to an array to get returned. I know... since I'm adding 7and it's within 7 days the first reoccurring event will always be within 7 days but that is not the case for monthly events or anything greater.
All cases are broken so I only included this one for simplicity. I can get date_Diff to return something like 7 or 12 or whatever the number may be but how can I check if that number is within the 7 days I want?
Thanks, I will include more information if needed to clarify any misunderstandings.
I'm not entirely sure what you are trying to do, but how about the following if you are just projecting dates forward and backwards and want to know if they are 7 days or more either way:
$today = date("Y-m-d");
$todaytime = strtotime($today);
$testdate = "2017-06-31";
$testtime = strtotime($testdate);
$back7days = strtotime("-7 days",$todaytime);
if($testtime < $back7days)
echo "X"; // do somthing if testdate was more than 7 days ago
$fwd7days = strtotime("+7 days", $todaytime);
if($testtime > $fwd7days)
echo "Y"; // do somthing if testdate is more than 7 days in future
Just make sure that you use less-than or less-than-and-equals comparators etc to handle the boundary conditions you need.

Repeat insert query with a different date given by a frequency

I'm building a system where an user can register activities. However the activities registered can repeat over the course of the year.
In order to prevent having the need that the user has to fill in the form to create an activity multiple times for each different date, I had the idea to add a textbox and a dropdown to the form to allow the user to fill in a frequency. The user can fill in a number in the textbox (for example "2") and select a value from the dropdown (for example "week"). So from that selection the activity has to be added to the database for the next 2 weeks on the same day.
However I have no idea how to let PHP adjust the date and add exactly 7 days to the selected date and repeat the same insert query with the new date, for every week/month/year selected from the given frequency.
EDIT 1:
I've tried this so far:
while ($i> 0)
{
$query2 = $this->db->connection->prepare("INSERT INTO activity(Act_Startdate) values (?)");
$query2->bind_param("s", $Startdate);
$query2->execute();
$Dates = date('d-m-Y', strtotime($Startdate . '+ 1 days'));
$Startdate = date('d-m-Y', strtotime($Dates));
$i--;
}
The first date insertion works, but the second one results 0000-00-00.
Read more about :
Date Time in PHP.
Date Interval in PHP
$numberPostedByUser = $_POST['your_input_name_in_form'];
$currentDate = new \DateTime(); // Getting current date
$iterator = 1;
while ($iterator <= $numberPostedByUser) {
$currentDate->add(new \DateInterval('P1D')); // Adding interval of one day in current date
$startDate = $currentDate->format('Y-m-d H:i:s'); // converting that day in convenient format we required
$query2 = $this->db->connection->prepare("INSERT INTO activity(Act_Startdate) values (?)");
$query2->bind_param("s", $startDate);
$query2->execute();
$iterator++; // increasing iterator for next loop
}
Hope may this code will help you.

Select Mysql with multiple greater and lower values

i am in need of a search query based on 6 values from 3 columns day, month, year, right now i have got it some how working only for month and year but i can not get the day to perform correctly.
for example if some one wants to search from day, month year to day month year.
my current query
//From
list($fy,$fm,$fd) = explode ('-', 2013-2-20);
//to
list($ty,$tm,$td) = explode ('-', 2014-9-1);
$add = " AND
( month >= '".$fm."'
AND year >='".$fy."') AND (
month <= '".$tm."'
AND year <= '".$ty."'
) ";
as you can see the day is not included, your time is much appreciated.
Going on with what you have. You would just add day in the same way you added month and year:
...
$add = " AND
( month >= '".$fm."'
AND year >='".$fy."'
AND day >='".$fd."') AND (
month <= '".$tm."'
AND year <= '".$ty."'
AND day <= '".$td."'
) ";
...
Since all the items are independent of each other, this works of the literal values are higher/lower in each item. Which is probably not what you want. You will need to convert the strings '2013-2-20' into DATE and then use those. This can be done with str_to_date(). So for example str_to_date('2013-2-20','%Y-%m-%d').
Notice: I'm aware that you cannot change the database but for future references it's a good idea to have a single DATE datatype for your database. It's not good design to separate them into separates things such as day, month, and year. As with using the DATE datatype it can easily find lower and higher dates by simply comparing the dates (along with date functions using dates can be used):
dateObj1 >= dateObj2 // dateObj1 is at a later date than dateObj2

Categories