looping and date growing 7 days according in php - php

I want to enter the data with looping and date growing 7 days according total input events
For example, on my form data input like this :
Input Date : 2015-11-27
Input Event : Meeting
Total Event : 3
This is my PHP code to insert with looping :
$date= date("Y-m-d", strtotime($_POST['date']));
$getDate= date('Y-m-d', strtotime($date. ' + 7 days'));
$event = $_POST['event'];
$ttl_event = $_POST['ttl_event'];
for ($i = 0; $i < $ttl_event; $i++) {
$query = mysql_query("INSERT INTO schedule values('','$getDate','$event')")or die(mysql_error());
}
And then finally in table, i want to like this :
id | date | event
1 2015-11-27 Meeting
2 2015-12-04 Metting
3 2015-12-11 Meeting
now, i always error with date always "2015-12-04" :(
please, correct my code.

You need to calculate future dates inside the loop, and increment the addition for each iteration. Meaning you wanna do +0, +7, +14...
for ($i = 0; $i < $ttl_event; $i++) {
$getDate= date('Y-m-d', strtotime($date.' +'.($i*7).'days'));
$query = mysql_query("INSERT INTO schedule values('','$getDate','$event')")
^ are you sure about this ?
or die(mysql_error());
}
Or you can write it like that
$getDate= date('Y-m-d', strtotime('+'.($i*7).'days', $date));
http://php.net/manual/fr/function.strtotime.php

Related

Monthly recurring event on specific date and skip any month if have less no of days compare to user's selected date

I am creating a app where user can create monthly event (Just like Google/Outlook), so if user has selected 31st date of any month and next month have 30 days than all next dates are changing to 30th.
Same goes with 30th, lets say user selected 30th of December than after Feb all next date is changing to 28th.
so if in next month days are lesser than user's selected date its changing the date to that.
Example :
Start Date : 2020-10-31
End Date : 2021-11-30
$diffInMonths = $startDate->diffInMonths($endDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$newStartDate = $i == 0 ? $startDate : $startDate->addMonthWithNoOverflow();
print('<pre>' . print_r($newStartDate->toDateString(), true) . '</pre>');
}
its giving output like this
2020-10-31
2020-11-30
2020-12-30
2021-01-30
2021-02-28
2021-03-28
2021-04-28
2021-05-28
2021-06-28
2021-07-28
2021-08-28
2021-09-28
2021-10-28
What i need is skip the month if in that month have less days than user;s selected date. With Above example the correct output should be
2020-10-31 //November has less than 31st day
2020-12-31
2021-01-31 //Feb has less than 31st day
2021-03-31 //April has less than 31st day
2021-05-31 //June & July has less than 31st day
2021-07-31
2021-08-31 //September has less than 31st day
2021-10-31
Struggling on this from last 2-3 days so any Kind of help or guidance will made my day :)
This might be dumb way of doing this, but as i am running out of time so here is solution
$dateRange = Carbon::parse($callPlanner->start_date)->toPeriod($callPlanner->end_date, 1, 'month');
$startDate = Carbon::parse($callPlanner->start_date);
foreach ($dateRange as $date) {
// compare the event date with end of month date
if ($startDate->day <= $date->endOfMonth()->day) {
//create new date with this month's year, month and event start date
$newDate = Carbon::createFromDate($date->endOfMonth()->year, $date->endOfMonth()->month, $startDate->day);
echo $newDate->toDateString(). "\n";
}
}
addMonths() add a month to a date. with no overflow, it makes the end of the next month, which is suppose 2020-02-29. in the next step it adds another month to 2020-02-29 and that makes the next date 2020-03-29 because it just added a month. you don't call it to update the date. so your solution would be using lastOfMonth()
$startDate = Carbon::parse('2020-01-31');
$endDate = Carbon::parse('2020-12-31');
$diffInMonths = $startDate->diffInMonths($endDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$newStartDate = $i == 0 ? $startDate : $startDate->addMonthWithNoOverflow()->lastOfMonth();
print('<pre>' . print_r($newStartDate->toDateString(), true) . '</pre>');
}
which will give you dates like
2020-01-31
2020-02-29
2020-03-31
2020-04-30
2020-05-31
2020-06-30
2020-07-31
2020-08-31
2020-09-30
2020-10-31
2020-11-30
2020-12-31
with addMonth you can't skip months that has less days. you have to check it manually with some condition. like
$startDate = Carbon::parse('2020-10-31');
$endDate = Carbon::parse('2021-11-30');
$highestDate = $startDate->format('d');
$diffInMonths = $startDate->diffInMonths($endDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$newStartDate = $i == 0 ? $startDate : $startDate->addMonthWithNoOverflow()->lastOfMonth();
if ($newStartDate->format('d') >= $highestDate) {
print('<pre>' . print_r($newStartDate->toDateString(), true) . '</pre>');
}
}
the output is
2020-10-31
2020-12-31
2021-01-31
2021-03-31
2021-05-31
2021-07-31
2021-08-31
2021-10-31
In such cases (similar to monthly subscriptions issues), it could be better to always start from the first date instead of chaining the additions:
$diffInMonths = $startDate->diffInMonths($endDate);
for ($i = 0; $i <= $diffInMonths; $i++) {
$newStartDate = $startDate->copy()->addMonthsWithNoOverflow($i + 1);
print('<pre>' . print_r($newStartDate->toDateString(), true) . '</pre>');
}
This way, you get last day of month is the day is not available but it does not change next iterations.
Note that ->copy() is not needed if you use CarbonImmutable.

php get last year range date

I have a user in a database with a creation_date. This user can run a job in my app UI, but he is limited by a number of job to run in one year.
This user has been created in 2014. I would like to do something like :
function runJob($user){
$nbRemainingJob = findReminingJobs($user);
if ($nbRemainingJob > 0){
runJob($user);
}
else {
die("no more credits";)
}
}
findReminingJobs($user){
$dateRangeStart = ?; //start date to use
$endRangeStart = ?; //end date to use
$sql = "SELECT count(*) FROM jobs WHERE user_id=?";
$sql .= "AND job_created_at BETWEEN ($dateRangeStart AND $endRangeStart)";
$res = $pdo->execute($sql, [$user->id]);
$done = $res->fetchOne();
return ($user->max_jobs - $done);
}
Every user's creation birthday, the $user->max_jobs is reset.
The question is how to find starting/ending date ? in other words, I would like to get a range of date starting from the user's creation date.
For example, if the user was created on 2014-04-12, my start_date should be 2018-04-12 and my end_date = 2019-04-11.
Any idea ?
First get the user register date from db and split it into Year, Month and Day like
$register= explode('-', $userCridate);
$month = $register[0];
$day = $register[1];
$year = $register[2];
Then get the current year like
$year = date("Y");
$dateRangeStart = $year."-".$month."-".$day; //start date to use
Now, check if this date is greater then today date, then use last year as starting date
$previousyear = $year -1;
$dateRangeStart = $previousyear ."-".$month."-".$day; //start date to use
$endRangeStart = date("Y-m-d", strtotime(date("Y-m-d", strtotime($dateRangeStart))
. " + 365 day"));
It is a idea, check if it work for you.
function getRange($registrationDate) {
$range = array();
// Split registration date components
list($registrationYear, $registrationMonth, $registrationDay) = explode('-', $registrationDate);
// Define range start year
$currentYear = date('Y');
$startYear = $registrationYear < $currentYear ? $currentYear : $registrationYear;
// Define range boudaries
$range['start'] = "$startYear-$registrationMonth-$registrationDay";
$range['end'] = date("Y-m-d", strtotime($range['start'] . ' + 364 day'));
return $range;
}
And for your example:
print_r(getRange('2014-04-12'));
Array
(
[start] => 2018-04-12
[end] => 2019-04-11
)
print_r(getRange('2014-09-13'));
Array
(
[start] => 2018-09-13
[end] => 2019-09-12
)
$created='2025-04-12';
$date=explode('-',$created);
if($date[0]<date("Y")){
$newDate=date('Y').'-'.$date[1].'-'.$date[2];
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
else{
$newDate=$created;
$dateEnding = strtotime($newDate);
$dateEnding = date('Y-m-d',strtotime("+1 year",$dateEnding));
}
echo 'starting date is: '.$newDate;
echo '</br>';
echo 'ending date is: '.$dateEnding;
This code will get the date you have and match it with the current year. If the year of the date you provided is equal or above the current year the start date will be your date and end date will be current date +1 year. Otherwise if the year is below our current year (2014) it will replace it with the current year and add 1 year for the end date. Some example outputs:
For input
$created='2014-04-12';
The output is :
starting date is: 2018-04-12
ending date is: 2019-04-12
But for input
$created='2025-04-12';
The outpus is :
starting date is: 2025-04-12
ending date is: 2026-04-12
The solution that match my need :
$now = new DateTime();
$created_user = date_create($created);
$diff = $now->diff($created_user)->format('%R%a');
$diff = abs(intval($diff));
$year = intval($diff / 365);
if ($year == 0){
$startDate=$created_user->format("Y-m-d");
}else{
$startDate=$created_user->add(new DateInterval("P".$year."Y"))->format("Y-m-d");
}
The problem was to define the starting date that is comprised in the one year range max from the current date and starting from the user's creation date.
So if the user's creation_date is older than one year, than I do +1 year, if not, take this date. the starting date must not be greater than the current date_time
thanks to all for your help

Getting the sum of sales per year MYSQL PHP

I want to get the sales per year I have this code (please see below), that gets the column name and format it into (please see below). I have start date and end date I want to get the all the months between the two years. For example start date = 01/01/2017 and end date = 01/01/2018 I want go get the months between them and format it into SUM(JAN_2017) AS JAN_2017, etc and at the same time get the sum of all the months for the year 2017 and 2018.
SCREENSHOT OF MY TABLE
THIS IS MY COLUMN NAME SAMPLE (PLEASE REFER TO THE SCREENSHOT):
JAN_2017, FEB_2017 UPTO DEC_2017
SAMPLE OUTPUT OF MY CODE:
SUM(JAN_2017) AS JAN_2017, etc.
CODE:
$start = new DateTime($_POST["start"]);
$end = new DateTime($_POST["end"]);
$smonth = (int)$start->format('Y')*12+(int)$start->format('n');
$emonth = (int)$end->format('Y')*12+(int)$end->format('n');
$firstmonth = min($smonth, $emonth);
$lastmonth = max($smonth, $emonth);
$months = array();
for ($i = $firstmonth; $i <= $lastmonth; $i++) {
$thism = new DateTime(sprintf('%04d-%02d-01', intdiv($i, 12), $i % 12));
$months[] = strtoupper($thism->format('M_Y'));
}
$m_total = implode(',', preg_replace('/^(.*)$/', 'SUM($1) AS $1', $months));
$m_average = implode(',', preg_replace('/^(.*)$/', 'AVG($1) AS $1', $months)
);

Increment days in PHP MySQL date [duplicate]

This question already has answers here:
Adding days to $Date in PHP
(12 answers)
Closed 5 years ago.
I have a table in MySQL with a date field (called NDate) which contains standard date values ("2017-04-17","2017-04-18", etc.).
Through PHP webpage, I am trying to take the system date (say today is 2017-04-17), and then pull all rows from the above table where NDate="2017-04-17". No issues till here.
I have a requirement to increment the day (starting today and going on for next 10 days - i.e. 2017-04-17 to 2017-04-26), and for each day report entries under a different heading like "Entries for 2017-04-17" which will list all rows having NDate 2017-04-17, "Entries for 2017-04-18" which will list all rows having NDate 2017-04-18.
I was trying to use a for loop with PHP date_modify function to increment the days one by one, but it is not showing any results.
Here are the selected pieces of code:
date_default_timezone_set('US/Eastern');
$datev = date("Y-m-d");
for ($x = 0; $x <= 10; $x++)
{
$datev=date_modify($date,"+$x days");
echo "before date format<br>"; // echo statement 1
echo "date is: $datev <br>"; // echo statement 2
$sql = "SELECT * FROM tablename where Ndate='$datev'";
echo "before result<br>"; // echo statement 3
...
...
...
}
Output on webpage shows only statement 1. But echo stats 2 and 3 are not printed.
You can increment days using strtotime function as a parameter to date function.
For 10 days, you can use for loop, to build an array of days. Then iterate over it, to execute queries you need.
$today = date('Y-m-d');
$dates=array($today);
for($i=1;$i<10;$i++) {
$NewDate=date('Y-m-d', strtotime("+".$i." days"));
$dates[]=$NewDate;
}
foreach($dates as $dt) {
// sql stuff here
echo "date is: $dt <br>";
$sql = "SELECT * FROM tablename where Ndate='$dt'";
echo "before result<br>";
// .....
}
This code should work for your case. If any problems, just let me know.
Try this:
$start = strtotime(date('Y-m-d'));
$end = strtotime(date('Y-m-d', strtotime('+10 days')));
while($start <= $end)
{
$date = date('Y-m-d', $start);
//use $date to do stuff
//SELECT * FROM tablename where Ndate='$date'
$start = strtotime("+1 day", $start);
}

php for loop for date increment each time

I want to loop a date so that every time date is increment by previous date. my code is here. plz reply anyone, thanks in advance
$today = date('Y-m-d');
for($i=1; $i<=4; $i++){
$repeat = strtotime("+2 day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
I want result as if today is 2016-04-04 than, 2016-04-06, 2016-04-08, 2016-04-10, 2016-04-12.
actually i want to make a reminder date where user enter reminder. lets a user want to add reminder today and want repeat it 5 time after 2days, 3days or what ever he wants, in next comming day. than how i repeat date with for loop.
Try this:
<?php
$today = date('Y-m-d');
for($i=1; $i<=4; $i++)
{
$repeat = strtotime("+2 day",strtotime($today));
$today = date('Y-m-d',$repeat);
echo $today;
}
Output:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
The easiest way is what answer
aslawin
The below example is to go through the date
$begin = new DateTime($check_in);
$end = new DateTime($check_out);
$step = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $step, $end);
foreach ($period as $dt)
{
<sample code here>
}
You can try this:
$today = date('Y-m-d');
for($i=1; $i<=8; $i++){
if($i%2 == 0){
$repeat = strtotime("+$i day",strtotime($today));
echo $rdate = date('Y-m-d',$repeat);
}
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
In this example, you can use $i%2 == 0 with limit <= 8
Use a for loop with base 2, then directly output your dates:
for( $i=2; $i<9; $i=$i+2 )
{
echo date('Y-m-d', strtotime( "+ $i days" )) . PHP_EOL;
}
Result:
2016-04-06
2016-04-08
2016-04-10
2016-04-12
actually i want to make a reminder date where user enter reminder.
lets a user want to add reminder today and want repeat it 5 time after
2days, 3days or what ever he wants, in next comming day. than how i
repeat date with for loop.
I'll help with the above. First of all I will just say I have a huge personal preference towards the DateTime object over simply using date it's more flexible and a hell of a lot more readable in my opinion, so when working with dates I would always suggest using that over date()
So here is some Code:
$date = new DateTime(); // Pretend this is what the User entered. We got it via $_POST or something.
$interval = 2; // Repeat x times at y day intervals. (Not including the initial)
$repeatAmount = 2; // Repeat the reminder x times
for ($i = 0; $i <= $repeatAmount; ++$i) {
echo $date->format('d/m/Y');
$date->modify('+'. $interval .' day');
}
$date = new DateTime()Imagine this is the date the user entered, this is our starting point, our first reminder will at this time.
$interval and $repeatAmount are the interval in days, i.e. I want this to every 2 days and the amount of times you want it to repeat, in our example 2.
for ($i = 0; $i <= $repeatAmount; ++$i) { We want to loop as many times as the user says they want to repeat. Little note ++$i tends to be a very minor performance boost over $i++ in some scenarios, so it is usually better to default to that unless you specifically need to use $i++
echo $date->format('d/m/Y'); Simply print out the date, i'll let you handle the reminder logic.
$date->modify('+' . $interval . ' day'); Increment the dateTime object by the interval that the user has asked for, in our case increment by 2 days.
Any questions let me know.

Categories