php timeout on for loop with dates - php

I want to get an array of dates within a period. To do so I thought up a for loop (seems simple enough...) But when I run it even with for the dates of 1 month it times out.
This is my php:
$startdate = '2018-01-31';
$recurring = '2';
switch($recurring) {
case '1':
$period = '+1 day';
break;
case '2':
$period = '+1 week';
break;
case '3':
$period = '+1 month';
break;
case '4':
$period = '+3 months';
break;
case '5':
$perion = '+1 year';
break;
default:
$period = null;
break;
}
$dates = [];
if($period !== null) {
for($date = $startdate; $date < strtotime('+1 month', $startdate); strtotime($period, $date)) {
$dates[] = $date;
}
}
echo json_encode($dates);

Increasing $date with $date = strtotime($period, $date) in the increment part of the for loop should keep it from timing out, but there are a couple of other improvements that could be made.
First I'd recommend calculating your end date once before the loop to avoid extra strtotime calls each time it checks the continuation condition.
$end = strtotime("$startdate +1 month");
Then, set $date = strtotime($startdate) in the initialization part, or you'll get a date string instead of a timestamp as the first value in your $dates array.
for ($date = strtotime($startdate); $date < $end; $date = strtotime($period, $date)) {
$dates[] = $date;
}

Related

Get 3 future day dates with php

I want to creat a table for listing 3 future days with day name and date for my online shopping.
I try this code but it doesn't work correctly :
function week_from_monday($date) {
// Assuming $date is in format DD-MM-YYYY
list($day, $month, $year) = explode("-", $_REQUEST["date"]);
// Get the weekday of the given date
$wkday = date('l',mktime('0','0','0', $month, $day, $year));
switch($wkday) {
case 'Monday': $numDaysToMon = 0; break;
case 'Tuesday': $numDaysToMon = 1; break;
case 'Wednesday': $numDaysToMon = 2; break;
case 'Thursday': $numDaysToMon = 3; break;
case 'Friday': $numDaysToMon = 4; break;
case 'Saturday': $numDaysToMon = 5; break;
case 'Sunday': $numDaysToMon = 6; break;
}
// Timestamp of the monday for that week
$monday = mktime('0','0','0', $month, $day-$numDaysToMon, $year);
$seconds_in_a_day = 86400;
// Get date for 7 days from Monday (inclusive)
for($i=0; $i<7; $i++)
{
$dates[$i] = date('Y-m-d',$monday+($seconds_in_a_day*$i));
}
return $dates;
}
$ddate = date('Y-m-d');
$date = new DateTime($ddate);
$week = $date->format("W");
$week_number = $week;
$year = date('Y');
for($day=5; $day<=30; $day++)
{
echo date('m/d/Y', strtotime($year."W".$week_number.$day))."\n";
}
Here is my code but I want to get this :
today : Sun
Monday 30
Tuesday 31
Wednesday 1
To get the next 3 upcoming dates, you can simplify this a lot using date and strotime.
Try this code:
function nextThreeDays($date) {
$dateTs = strtotime($date);
// Dont need this, but I leave it for educational purpose:
// $day_of_week = date("N", $dateTs) - 1; // Mon=0 Tue=1 Wed=2 ...
// $monday_time = strtotime(date("d.m.Y H:i:s", $dateTs) . " -".$day_of_week." days"); // timestamp of monday of week of $date
for($i = 1; $i <= 3; $i++) {
echo date('m/d/Y', strtotime(date("d.m.Y H:i:s", $dateTs) . " +".$i." days"))."\n";
}
}
// Put in "today : Sun"
nextThreeDays("29.01.2023");
Outputs:
// Monday 30 Tuesday 31 Wednesday 1
01/30/2023
01/31/2023
02/01/2023

Need to add a specified numbers of days to a selected date

Need to add a specified numbers of days to a selected date. Not the current date. Im using strtotime in this fashion:
$date = $_POST['r_date'];
$r_date = $date;
$txts_rental = $_POST['txts_rental'];
switch ($txts_rental){
case "250.00":
$s_length = "30";
break;
case "575.00":
$s_length = "90";
break;
case "975.00":
$s_length = "180";
break;
case "1200.00":
$s_length = "365";
break;
}
$rn_date = date( "Y-m-d", strtotime( "$s_length day" ) );
the date( "Y-m-d" needs to be the the $r_date variable in order to get the renewal date from the inputted date
You can use
$EndDateTime = DateTime::createFromFormat('d/m/Y', "16/07/2017");
$EndDateTime->modify('+6 days');
echo $EndDateTime->format('d/m/Y');
or
$today = "2015-06-15"; // Or can put $today = date ("Y-m-d");
$fiveDays = date ("Y-m-d", strtotime ($today ."+5 days"));
You need to change your method as below. add the target date in second parameter so that the date not added in current date
$date = $_POST['r_date'];
$r_date = $date;
$txts_rental = $_POST['txts_rental'];
switch ($txts_rental){
case "250.00":
$s_length = "30";
break;
case "575.00":
$s_length = "90";
break;
case "975.00":
$s_length = "180";
break;
case "1200.00":
$s_length = "365";
break;
}
$rn_date = date( "Y-m-d", strtotime( "$date +".$s_length." day" ) );

Function for selecting next Day If the last day is weekend

I am trying to create a function that checks the range of date. If the last date is an weekend it will select the next day. Suppose, Today is 1 March 2016. If someone add 5 with it, it will make the result 7 March 2016. Because 6 March is Weekend. I have written this code. But it is not working and I cannot find where is the problem. The code is as below:
<?php
$date = "2016-02-29";
$numOfDays = 8;
$futureDate = strtolower(date("l",strtotime($date." +".$numOfDays."days")));
$weekend1= "friday";
$weekend2= "saturday";
if($futureDate != $$w1 || $futureDate != $w2){
$finalDate = date("Y-m-d",strtotime($futureDate));
}
else{$finalDate = date("Y-m-d",strtotime($futureDate ."+1 day"));}
echo $finalDate;
?>
Check this:
<?php
$date = "2016-02-29";
$numOfDays = 11;
$futureDate = strtolower(date("l",strtotime($date ."+".$numOfDays."days")));
$futureDate1 = strtolower(date("Y-m-d",strtotime($date ."+".$numOfDays."days")));
$weekend1= "friday";
$weekend2= "saturday";
if($futureDate == $weekend1){
$finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+2 days"));
}
if ($futureDate == $weekend2){
$finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+1 days"));
}
echo $finalDate1;
?>
March 6th, 2016 is a Sunday, but you're checking for Friday and Saturday, you need to check for Saturday and Sunday instead, for the weekend. Also, your variable names need to match, and for Saturday you'll need to add two days to get the next weekday.
<?php
$date = "2016-02-29";
$numOfDays = 8;
$day = 86400;//one day is 86400 seconds
$time = strtotime($futureDate + $numOfDays * $day);//converts $futureDate to a UNIX timestamp
$futureDate = strtolower(date("l", $time));
$saturday = "saturday";
$sunday = "sunday";
if($futureDate == $saturday){
$finalDate = date("Y-m-d", $time + 2 * $day);
}
else if($futureDate == $sunday){
$finalDate = date("Y-m-d", $time + $day);
}
else{
$finalDate = date("Y-m-d", $time);
}
echo($finalDate);
?>
#Fakhruddin Ujjainwala
I have changed in your code and it works now perfect. Thanks. the code is now as below:
<?php
$date = "2016-02-29";
$numOfDays = 4;
$futureDate = strtolower(date("l",strtotime($date ."+".$numOfDays."days")));
$futureDate1 = strtolower(date("Y-m-d",strtotime($date ."+".$numOfDays."days")));
$weekend1= "friday";
$weekend2= "saturday";
if($futureDate == $weekend1){
$finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+2 days"));
}
else if ($futureDate == $weekend2){
$finalDate1 = date("Y-m-d",strtotime($futureDate1 ."+1 days"));
}
else{
$finalDate1 = date("Y-m-d",strtotime($futureDate1));
}
echo $finalDate1;
?>

PHP DateInterval. Go back to the beginning of the year

I would like to write a method which I can give a period of time (Like: yearly, monthly...) and it returns me an anterior date according to this period of time given.
Here is my code:
public function callRuleCeilling($period)
{
$start = new \DateTime();
switch ($period) {
case 'weekly':
$dateInterval = 'P7D';
break;
case 'monthly':
$dateInterval = 'P1M';
break;
case 'quaterly':
$dateInterval = 'P3M';
break;
case 'half-yearly':
$dateInterval = 'P6M';
break;
case 'yearly':
$dateInterval = 'P1Y';
break;
default:
$dateInterval = 'P1Y';
}
$start->sub(new \DateInterval($dateInterval));
return $start
}
My example problem:
If I put a starting date in the middle of the year with a yearly period. I want it to stop at the beginning of the year.
And I would like the same for monthly period (Stop at the beginning of the month) etc...
Does it exist a PHP function with do that? I can't find it.
Please highlight me.
Thanks fo the highlight. It allowed me to did that way:
public function callRuleCeilling($period)
{
$start = new \DateTime();
$month = 'January';
switch ($period) {
case 'weekly':
$timestampMonday = strtotime('last monday', strtotime('tomorrow'));
$start = $start->setTimestamp($timestampMonday);
break;
case 'monthly':
$month = $start->format('F');
$start = new \DateTime('first day of '.$month);
break;
case 'quaterly':
$monthNumber = $start->format('n');
if($monthNumber >= 1) $month = 'January';
if($monthNumber >= 5) $month = 'May';
if($monthNumber >= 9) $month = 'September';
$start = new \DateTime('first day of '.$month);
break;
case 'half-yearly':
$monthNumber = $start->format('n');
if($monthNumber >= 1) $month = 'January';
if($monthNumber >= 7) $month = 'July';
$start = new \DateTime('first day of '.$month);
break;
case 'yearly':
$start = new \DateTime('first day of January');
break;
default:
$start = new \DateTime('first day of January');
}
return $start;
}

Get month name using start date and end date?

$startDate = "2014-03-01";
$endDate= "2014-05-25";
Result required: March, April, May;
for that PHP delivers the DatePeriod object. Just have a look at the following example.
$period = new DatePeriod(
new DateTime('2014-03-01'),
DateInterval::createFromDateString('1 month'),
new DateTime('2014-05-25')
);
foreach ($period as $month) {
echo strftime('%B', $month->format('U'));
}
A quick solution is to parse each day and check it month:
$startDate = "2014-03-01";
$endDate = "2014-05-25";
$start = strtotime($startDate);
$end = strtotime($endDate);
$result = array();
while ( $start <= $end )
{
$month = date("M", $start);
if( !in_array($month, $result) )
$result[] = $month;
$start += 86400;
}
print_r($result);
I believe it can be done much efficient by new OOP (DateTime object) approach, but this is fast and no-brain if you need to make it work.
<?php
$startDate = "2014-03-01";
echo date('F',strtotime($startDate));
?
$date = date('F',strtotime($startDate));
For full month representation (ie Januaray, February, etc)
$date = date('M',strtotime($startDate));
For abbreviated...(ie Jan, Feb, Mar)
REFERENCE
If you wanna echo out those months in between based on two dates....
$d = "2014-03-01";
$startDate = new DateTime($d);
$endDate = new DateTime("2014-05-01");
function diffInMonths(DateTime $date1, DateTime $date2)
{
$diff = $date1->diff($date2);
$months = $diff->y * 12 + $diff->m + $diff->d / 30;
return (int) round($months);
}
$t = diffInMonths($startDate, $endDate);
for($i=0;$i<$t+1;$i++){
echo date('F',strtotime($d. '+'.$i.' Months'));
}
PHP SANDBOX EXAMPLE

Categories