Add 1 month to dates in for loop in PHP - php

I want to add 1 month in due date for every iteration of for loop. Here's my code below.
$qt = 3;
$sales_due_date = 2015-09-21;
for($i=0;$i<$qt;$i++){
$time = date('Y-m-d', strtotime('+1 month', strtotime($sales_due_date)));
$due_dates[] = $time;
}
The result is
Array ( [0] => 2015-10-21 [1] => 2015-10-21 [2] => 2015-11-21)
I want the result to be like below
Array ( [0] => 2015-09-21 [1] => 2015-10-21 [2] => 2015-11-21)

Your code does not update the $sales_due_date and so it will always return the same value. Plus, if you want the starting value, you need to change the logic a bit. Perhaps this might work better for you:
$qt = 3;
$sales_due_date = "2015-09-21";
// create a time stamp of the date
$time = strtotime($sales_due_date);
for($i=0;$i<$qt;$i++){
// convert timestamp back to date string
$date = date('Y-m-d', $time);
$due_dates[] = $date;
// move to next timestamp
$time = strtotime('+1 month', $time)
}

this should give expected result
$qt = 3;
$sales_due_date = "2015-09-21";
for ($i = 0; $i < $qt; $i++)
{
$due_dates[] = $sales_due_date;
$time = date('Y-m-d', strtotime('+1 month', strtotime($sales_due_date)));
$sales_due_date = $time;
}
output
Array
(
[0] => 2015-09-21
[1] => 2015-10-21
[2] => 2015-11-21
)

try this
$qt = 3;
$sales_due_date = 2015-09-21;
$time="";
for($i=0;$i<$qt;$i++){
if($time == "")
{
$time = date('Y-m-d', strtotime('+1 month', strtotime($sales_due_date)));
}
else{
$time = date('Y-m-d', strtotime('+1 month', strtotime($time)));
}
$due_dates[] = $time;
}

Related

how to receive all days between 2 dates in laravel

consider that i have 2 dates like below in my view :
{{$property->start_date }} //which is for example 3/20/219
and another date
{{$property->end_date }} //which is for example 3/28/219
now i want to some how print these 8 days of difference as 8 col-lg-1 some how like below code
#while($property->start_date <= $property->end_date)
//here i want to print dates in col-lg-1 i dont know how to access the day and if the while loop is working right or no
how can i achieve that in blade considering this that i am doing this in my view and is it reasonable at all to do it in view or not .
You can use the CarbonPeriod from Carbon
something like this
$ranges = CarbonPeriod::create('2019-03-01', '2019-03-31');
To print each date you can use the loop
foreach ($ranges as $date) {
echo $date->format('Y-m-d');
}
Or you can convert it to array as well
$dates = $ranges->toArray();
Return all dates between two dates in php:
Using DatePeriod and DateTime:
$begin = new DateTime($property->start_date); // your start date 2019-03-20
$begin = $begin->modify( '+1 day' );
$end = new DateTime($property->end_date); // your end date 2019-03-28
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach ($daterange as $date) {
echo '<pre>'.$date->format('Y-m-d').'<pre>';
}
Output:
2019-03-21
2019-03-22
2019-03-23
2019-03-24
2019-03-25
2019-03-26
2019-03-27
Using strtotime:
// Declare two dates
$Date1 = $property->start_date; // 2019-03-20
$Date2 = $property->end_date; // 2019-03-28
// Declare an empty array
$array = array();
// Use strtotime function
$start = strtotime($Date1. '+1 day');
$end = strtotime($Date2. '-1 day');
// Use for loop to store dates into array
// 86400 sec = 24 hrs = 60*60*24 = 1 day
for ($currentDate = $start; $currentDate <= $end; $currentDate += (86400)) {
$Store = date('Y-m-d', $currentDate);
$array[] = $Store;
}
// Display the dates in array format
echo '<pre>';
print_r($array);
echo '<pre>';
Output:
Array
(
[0] => 2019-03-21
[1] => 2019-03-22
[2] => 2019-03-23
[3] => 2019-03-24
[4] => 2019-03-25
[5] => 2019-03-26
[6] => 2019-03-27
)
I hope it would helpful.
If you want to get date diff , you can use Carbon and diffInDays .
$date1 = Carbon::parse($property->start_date);
$date2 = Carbon::parse($property->end_date );
$diff = $date1->diffInDays($date2);
dd($diff);
You can try this on template directly (only if there no way or if it's difficult to pass it from controller to view)
#php
$date1 = \Carbon\Carbon::parse('2019-01-31 10:15:23');
$date2 = \Carbon\Carbon::parse('2019-02-15 10:15:23');
$diff = $date1->diffInDays($date2);
#endphp
<div>{{$diff}}</div>
but if you do it in controller and send it to template it would be better

Finding last 7 working days in PHP

I am trying to find out last 7 working days (excluding Saturday and Sunday) from the current day. I am able to get last 7 days of the week, but unable to get the 7 working day's.
//code to found last 7 days
$date = '04/30/2009'; // set current date
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 7; $i++, $ts += 86400){
print date("m/d/Y l", $ts) . "\n". "<br>";
}
But I wanted to find last 7 working days. Thanks in advance!
It's relatively easy to work backwards from a point int time to find the "working days" but finding "holidays" is far more complicated and would require considerably more code than this I suspect.
Using the DateTime class you can use the sub method to subtract whatever interval value you wish, in this case P1D is one day.
$strdate='04/30/2009';
$days=11;
$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1D');
$start=new DateTime( date( DATE_COOKIE, strtotime( $strdate ) ), $timezone );
$end=new DateTime( date( DATE_COOKIE, strtotime( $start->format( DATE_COOKIE ) . '-' . $days .' days' ) ), $timezone );
$dates=array();
while( $start->sub( $interval ) > $end ){
/* is the day integer less than 6(sat)? */
if( $start->format('N') < 6 && count( $dates ) < 7 ) $dates[]=$start->format( DATE_COOKIE );
}
echo '<pre>',print_r( $dates,true ),'</pre>';
This outputs:
Array
(
[0] => Wednesday, 29-Apr-09 00:00:00 BST
[1] => Tuesday, 28-Apr-09 00:00:00 BST
[2] => Monday, 27-Apr-09 00:00:00 BST
[3] => Friday, 24-Apr-09 00:00:00 BST
[4] => Thursday, 23-Apr-09 00:00:00 BST
[5] => Wednesday, 22-Apr-09 00:00:00 BST
[6] => Tuesday, 21-Apr-09 00:00:00 BST
)
I did a little playing around with a public api for getting public holiday information and cobbled the following together...I don't know what sort of coverage this api has for different countries but might be worth investigation.
Different country and region codes can be found here
$api='http://kayaposoft.com/enrico/json/v1.0/';
$params=array(
'action' => 'getPublicHolidaysForDateRange',
'fromDate' => '',
'toDate' => '',
'country' => 'eng' #England
);
$strdate='2017/12/30';
$days=7;
$timezone=new DateTimeZone('Europe/London');
$interval=new DateInterval('P1D');
$start=new DateTime( date( 'Y-m-d', strtotime( $strdate ) ), $timezone );
$end=new DateTime( date( 'Y-m-d', strtotime( $start->format( 'Y-m-d' ) . '-' . $days .' days' ) ), $timezone );
$params['fromDate']=$end->format('d-m-Y');
$params['toDate']=$start->format('d-m-Y');
$query=http_build_query( $params );
$url=$api.'?'.$query;
$json=json_decode( file_get_contents( $url ) );
if( json_last_error() !== 0 ){
$json=false;
}
function isholiday( $obj=false, $y=0, $m=0, $d=0 ){
if( $obj && !empty( $obj ) ){
foreach( $obj as $item ){
$date=$item->date;
if( $date->day==$d && $date->month=$m && $date->year==$y ) return $item->localName;
}
}
return false;
}
$dates=array();
while( $start->sub( $interval ) > $end ){
if( $start->format('N') < 6 && count( $dates ) < $days ) {
$holiday=isholiday( $json, $start->format('Y'), $start->format('m'), $start->format('d') );
$date=$start->format( 'Y-m-d' );
$dates[]=$holiday ? $date .' - '.$holiday : $date;
}
}
echo '<pre>',print_r( $dates, true ),'</pre>';
This outputs the following:
Array
(
[0] => 2017-12-29
[1] => 2017-12-28
[2] => 2017-12-27
[3] => 2017-12-26 - Boxing Day
[4] => 2017-12-25 - Christmas Day
)
Finding holidays will be more complicated.
One solution can be like saving the holidays in advance and skip them if they comes in the condition.
One simple solution for your problem can be like this.
<?php
$holiday = array(
'2017-12-16' => 'Victory Day of Bangladesh',
'2017-12-25' => 'Christmas'
);
$i = 0;
$work_day = '2017-12-26';
while($i != 7)
{
$work_day = date('Y-m-d', strtotime('-1 day', strtotime($work_day)));
$day_name = date('l', strtotime($work_day));
if($day_name != 'Saturday' && $day_name != 'Sunday' && !isset($holiday[$work_day]))
{
echo $work_day."\n";
$i++;
}
}
?>
If you need 7 days without weekend days you need to check the numeric representation of the day of the week, ie "N" Format of date('N').
When skipping 2 weekend days you need increase the for loop to 9 days:
//code to found last 7 days
$date = '04/30/2009'; // set current date
// parse about any English textual datetime description into a Unix timestamp
$ts = strtotime($date);
// calculate the number of days since Monday
$dow = date('w', $ts);
$offset = $dow - 1;
if ($offset < 0) {
$offset = 6;
}
// calculate timestamp for the Monday
$ts = $ts - $offset*86400;
// loop from Monday till Sunday
for ($i = 0; $i < 9; $i++, $ts += 86400){
if(date("N", $ts) < 6){ // day code is less then weekday 6 & 7
print date("m/d/Y l", $ts) . "\n". "<br>";
}
}
https://eval.in/916514
Simple code with possibility to add holidays:
<?php
$date = new DateTime('03/02/2009');
$interval = new DateInterval('P1D');
function isWorkingDay($date)
{
$weekDay = $date->format('w');
if ($weekDay == 0) // sunday
return false;
if ($weekDay == 6) // saturday
return false;
if ($date->format('m-d') == '07-05') // your check, example 5th July
return false;
return true;
}
$workingDays = [];
while(count($workingDays) != 7) {
if(isWorkingDay($date)) {
$workingDays[] = clone $date;
}
$date->sub($interval);
}
foreach($workingDays as $workingDay) {
echo $workingDay->format('Y-m-d') . ', ';
}
Result - list of days without weekend days:
2009-03-02, 2009-02-27, 2009-02-26, 2009-02-25, 2009-02-24, 2009-02-23, 2009-02-20,

PHP Get recurring dates for specific weekday

How to get all recurring dates for chosen week of the day?
For example, today is Wednesday 15/02/2017 and if I choose Thursday how to get next 5 dates starting next Thursday like:
$dates = array(
[0] => "16/02/2017",
[1] => "23/02/2017",
[2] => "02/03/2017",
[3] => "09/03/2017",
[4] => "16/03/2017");
If I choose Tuesday, get dates starting 21/02/2017, which is next Tuesday
You can use strtotime to generate timestamps for this dates, the date function can generate actual dates.
<?php
// Array for dates
$dates = [];
// Get next thursday
$date = strtotime('thursday');
$dates[] = $date;
// Get the next four
for ($i = 0; $i < 4; $i++)
{
$date = strtotime('+1 week', $date);
$dates[] = $date;
}
// Echo dates
foreach ($dates as $date)
echo date('Y-m-d', $date);
Take a look at this post
Using that idea:
//Get First Thursday
$date = new DateTime();
$date->modify('next thursday');
echo "<br/>Starting Thursday: " . $date->format('d/m/Y');
//Loop over next 4 Thursdays
for($i = 2; $i <= 5; $i++)
{
$date->modify('+7 days');
echo "<br/>Thursday " . $i . ": " . $date->format('d/m/Y');
}

Get all occurrence of specific day in a month

Suppose i have a month June 2014. Now i want to get dates of all Mondays in June month.
like Monday is coming on following days so answer will be like following
2014-06-02
2014-06-09
2014-06-16
2014-06-23
2014-06-30
please do not give be static solution only for June. I need dynamic solution for every month and purely in PHP.
Try this -
<?php
$startDate = "2014-06-01";
$endDate = "2014-06-30";
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
for($i = strtotime('Monday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
echo date('l Y-m-d', $i).PHP_EOL;
DEMO:
http://3v4l.org/n4ULA
Try to create an array with all your date with day on key (with variable $day and $date):
$array = array("Monday" => "2014-06-02", "Tuesday" => "2014-06-03", "Wednesday" => "2014-06-04");
You create a loop to reach all the result :
foreach($array as $key => $value {
if($key == "Monday")
echo $value;
}
Using the above, I created this so you can use variables to define the month, year, and selected weekday.
$month = "6";
$year = "2022";
$weekday = "Tuesday";
$d=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$first_date_of_month = $year."-".$month."-01";
$last_date_of_month = $year."-".$month."-".$d;
$startDate = strtotime($first_date_of_month);
$endDate = strtotime($last_date_of_month);
for($i = strtotime($weekday, $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
echo "<br />". date('l Y-m-d', $i).PHP_EOL;

How to sum time in php?

PHP: How to sum the result of a foreach statement?
Below is my working code. As you will see, I'm trying to count the days in each month and then sum them.
// A function to calculate days in a given month using just the date
function daysInMonths($date)
{
$month = date("m", strtotime($date));
$year = date("Y", strtotime($date));
$num = cal_days_in_month(CAL_GREGORIAN, $month, $year);
return $num;
}
// A function that places the date of an unknown number of months into an array:
function getNextMonths($date, $numberOfMonths)
{
$timestamp_now = strtotime($date);
$months[] = date('Y-m-d', $timestamp_now);
for($i = 1;$i <= $numberOfMonths; $i++)
{
$months[] = date('Y-m-d', (strtotime($months[0].' +'.$i.' month')));
}
// counts the days in each month:
$j=0;
foreach ($months as $days)
{
echo "$j:".daysInMonths($days)."<br>";
++$j;
}
print_r($months);
}
getNextMonths('2011-11-1', '4');
Current output:
Array (
[0] => 2011-11-01
[1] => 2011-12-01
[2] => 2012-01-01
[3] => 2012-02-01
[4] => 2012-03-01
)
After counting:
0:30
1:31
2:31
3:29
4:31
This is all correct, I'm just having trouble summing the array after I have the days of the month counted.
$tot = 0;
foreach ($months as $days) {
$tot += daysInMonths(days);
}
echo $tot;
array_sum() - http://php.net/manual/en/function.array-sum.php
$t = array(
31,
28,
31
);
echo array_sum($t); // 90
Add a counter like you use in for while etc!!

Categories