Auto increment years in loop every year [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to increment date with 1 (day/year) in PHP?
Im not really sure where to begin with this but im trying to make a year start at 1928 and stop at 1948 and for every year the years increment by one so since its 2012 the date ranges are 1928 - 1948 and for 2013 it would be 1929 - 1949 and 2014 would be 1930 - 1950 and so on...
right now i just have a basic loop for when to start and stop the years but its not too dynamic, like i said im pretty much at a blank on where to begin other then date('Y')+1.
for($i=1928;$i<=date('Y');$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
if($i == '1948'){break;}
}

So you want it to go between current year minus 84 and the current year minus 64? Use this code:
$firstYear = (int)date('Y') - 84;
$lastYear = $firstYear + 20;
for($i=$firstYear;$i<=$lastYear;$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}
Edit: updated for performance. Current year is determined before the loop (per Pitchinnate's comment).

Try this:
$year = date('Y');
$add = $year - 2012;
$min = 1928 + $add;
$max = $min + 20;
for($i=$min;$i<=$max;$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}
I isn't a good idea to have date('Y') or any evaluations done on the for loop as it gets calculated every time through the loop. Article about this.

Something like this?
$base_year = 2012;
$start_year = $base_year - 84;
$end_year = $start_year + 20;
for( $i = $start_year; $i <= $end_year; $i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}

for($i =0; $i <= 20 ;$i++)
{
$year = date('Y') - 84 + $i;
echo '<option value='.$year.'>'.$year.'</option>';
}

It looks like you have a constant with how far back you want the date range to be from the current year that you can use to write a loop that will work for you.
Since it's 2012 now, and you want the range to start at 1928 when it's 2012, then we can use 2012 - 1928 = 84, so the year that starts the range should always be 84 less than the current year.
Therefore we could write code like:
$startingYear = date('Y') - 84;
$endingYear = $startingYear + 20;
for ($i = $startingYear;$i <= $endingYear;$i++)
{
echo '<option value='.$i.'>'.$i.'</option>';
}

Related

How to increment day in loop PHP [duplicate]

This question already has answers here:
PHP: Return all dates between two dates in an array [duplicate]
(26 answers)
Closed 3 years ago.
I have the following code
I get a date begin and date end
$dateBegin = date('2019-11-15');
$dateEnd = date('2019-11-20');
for($i = 0; $i < 5; $i++) {
...
}
//output
2019-11-15 - 2019-11-20
2019-11-21 - 2019-11-26
2019-11-27 - 2019-11-32
2019-11-33 - 2019-11-38
2019-11-39 - 2019-11-44
how to implement a loop add 5 days between begin and end day ?
Use strtotime().
Note that I had to use 6 days to get your desired outcome, not 5.
<?php
$dateBegin = date('2019-11-15');
$dateEnd = date('2019-11-20');
for($i = 0; $i < 5; $i++) {
echo "{$dateBegin} - {$dateEnd}\r\n";
$dateBegin = date('Y-m-d', strtotime($dateBegin. ' + 6 days'));
$dateEnd = date('Y-m-d', strtotime($dateEnd. ' + 6 days'));
}

Get the day number from a date [duplicate]

This question already has answers here:
PHP - How to get year, month, day from time string
(5 answers)
Closed 7 years ago.
I want to get the day number of a date.
For example my date is: 2015-12-31, it should return 365 and 2015-01-1 would be 1.
How can I do that?
EDIT: date('z') does not work for me, I dont want the current date
Use strtotime() — to parse about any English textual datetime description into a Unix timestamp. And getdate() — Get date/time information.
<?php
$day = getdate(strtotime("2015-12-31"));
echo $day['yday']+1; // output 365
?>
Try
<?php
$today = getdate(strtotime('2015-12-31'));
echo '<pre>';
print_r($today['yday'] + 1);
?>
Read GetDate
You can try it.
<?php
$day = 31;
$mon = 12;
$year = 2015;
$sum = 0;
$days = 0;
$month_day = array(31,28,31,30,31,30,31,31,30,31,30,31);
for ( $i = 0; $i < $mon; $i++){
$sum += $month_day[$i];
}
$days = $sum - ($month_day[$mon-1] - $day);
echo "$days";
?>
You may get day, mon, year from your expected date and make it integer. You should check the year is leap year or not. It may vary one day if it is a leap year. I think you shall do it.

Generate Friday Cutoff on PHP or MySQL [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Finding date range for current week, month and year
Can Anyone help me on how could I generate Friday cutoff using PHP or MySQL. below is the sample date range
...
2012-10-06 to 2012-10-12
2012-10-13 to 2012-10-19
2012-10-20 to 2012-10-26
...
2012-12-22 to 2012-12-28
2012-12-29 to 2013-01-04
Knowing the first saturday (the initial period) is easy to calculate the next friday (and looping the next saturday, next friday of second saturday....)
Check this code:
<?php
$saturday = '2012-10-06';
$next_friday = date('Y-m-d', strtotime('+6 days', strtotime($saturday)));
print "The next friday is $next_friday";
Try this code ...
function getCurrentWeek($start , $end){
$ts = strtotime($start);
$te = strtotime($end);
$days = round(abs($te-$ts)/86400);
$range = '';
$j = 0;
// generate dates
for ($i=0; $i<$days; $i++, $ts+=86400){
$temp_date = date("Y-m-d", $ts);
$d = (int) date('w',$ts);
switch ($d) {
case 5 :
if($j == 1)
$range .= $temp_date . "<br />" ;
$j = 0;
break;
case 6 :
$j = 1;
$range .= $temp_date . " TO " ;
break;
}
}
return $range;
}
echo getCurrentWeek('2012-10-06','2013-01-06');
Ps) You need to input correct start and end date where you have a Friday at the end ... or you will have XXXX-XX-XX TO EMPTY

Incrementing days if day is a workday

I need your help again.
This should be a function for php. I've got two dates. One is set by myDate and the other one is the date of today. I want to find out the number of days left to myDate, but saturday and sundy should be excluded. The result for this function would be 7...
How can I make it work?
<?php
myDate = "29.07.2010 "
DaysTillmyDate = 0
iterate day to myDate {
if (date/day is a weekday(Monday,Tuesday,Wednesday,Thursday, Friday))
increment DaysTillmyDate by 1
}
?>
A hint or any help would be much appreciated.
Faili
Quick iteration:
$days = 0;
for($i = time(); $i < (strtotime('29.07.2010') + 86400); $i=$i+86400)
{
$weekday = date('w', $i);
if($weekday > 0 && $weekday < 6)
{
$days++;
}
}
echo $days;
date('N', $theDate) gives you the day of the week (6 for Saturday and 7 for Sunday). From there, you can easily implement a function that does only counts workdays. On the other hand, this does not detect holidays.

List of all months and year between two dates in PHP

I am trying to explain the details so that this is easy to understand.
I want a list of month and year based on the difference of month and year.
I am implementing search functionality based on start month with year and end month with year.
So!
start Selection - 01(month)-2009 (Yr)
End selection 10(month)-2009 (Yr)
What I want from MySQL is:
Month Year
JAN 2009
FEB 2009
MAR 2009
APR 2009
MAY 2009
JUN 2009
JUL 2009
AUG 2009
SEP 2009
OCT 2009
FractalizeR answer is the right one.
Just let me expand by defining the functions:
function GetMonthsFromDate($myDate) {
$year = (int) date('Y',$myDate);
$months = (int) date('m', $myDate);
$dateAsMonths = 12*$year + $months;
return $dateAsMonths;
}
function GetDateFromMonths($months) {
$years = (int) $months / 12;
$month = (int) $months % 12;
$myDate = strtotime("$years/$month/01"); //makes a date like 2009/12/01
return $myDate;
}
PS: tried to post as a comment but the formating got screwed.
(Of course this functions could be rewritten as one liners but wanted to be more readable)
You need to write some functions to convert your dates to a number of months passed since certain date and back. For example, since Jan 1980.
Jan 1980 = 0;
Dec 1980 = 12;
Jan 1981 = 13 etc.
Then you just do simple "for" loop:
for ($i = GetMonthsFromDate($StartDate), $i <= GetMonthsFromDate($StopDate), $i++) {
echo(GetDateFromMonths($i));
}
Although FractalizeR answer is the correct one.
There is another option.
Taking advantage from the fact that that strtotime('2009/08/01 - 1 month') will do the right thing and delete 1 month.
<?php
$startDate = strtotime("$startYear/$startMonth/01");
$endDate = strtotime("$endYear/$endMonth/01");
$currentDate = $endDate;
while ($currentDate >= $startDate) {
echo date('Y/m',$currentDate);
$currentDate = strtotime( date('Y/m/01/',$currentDate).' -1 month');
}
Again a list of months
Here is the final answer which is worked very great
$startMonth= $_POST['startmonth'];
$startyear= $_POST['startyear'];
$cYear = $startyear;
$endMonth= $_POST['endmonth'];
$endyear= $_POST['endyear'];
$sql = "SELECT PERIOD_DIFF(".$endyear.$endMonth.", ".$startyear.$startMonth.")";
$queryRS = $db->query($sql);
$tmonthsarray = $db->fetchRow($c_jobsVat);
$totalmonths=tmonthsarray[0];
for($count=$startMonth; $count <= ($startMonth + $totalmonths);$count++)
{
$processYear = $startyear + intval( ( $count - 1 ) / 12 );
$processMonth= (( $count - 1 ) % 12 + 1);
$processMonthName= date('F', mktime(0,0,0,$count));
}
I wrote that function based on you guys's input. Check this out:
function CountTheMonth($startDate,$endDate,$order)
{
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
$ASC_Month = $startDate;
$DESC_Month = $endDate;
$Y_Axis = Array();
if($order == 'DESC')//Big to small
{
while ($DESC_Month >= $startDate)
{
$Y_Axis[] = date('F-Y',$DESC_Month);
$DESC_Month = strtotime( date('Y-m-d',$DESC_Month).' -1 month');
}
return $Y_Axis;
}
elseif($order == 'ASC')//Small to big
{
while ($ASC_Month <= $endDate)
{
$Y_Axis[] = date('F-Y',$ASC_Month);
$ASC_Month = strtotime( date('Y-m-d',$ASC_Month).' +1 month');
}
return $Y_Axis;
}
}
Your logic works great to get a list of months. But not sure how we can deal with years in this case.
Here is my code:
$startMonth= $_POST['startmonth'];
$startyear= $_POST['startyear'];
$endMonth= $_POST['endmonth'];
$endyear= $_POST['endyear'];
$sql = "SELECT PERIOD_DIFF(".$endyear.$endMonth.", ".$startyear.$startMonth.")";
$queryRS = $db->query($sql);
$tmonthsarray = $db->fetchRow($c_jobsVat);
$totalmonths= $tmonthsarray[0];
for($count=$startMonth; $count <= ($startMonth + $totalmonths);$count++)
{
echo "<BR>==>".date('F', mktime(0,0,0,$count)) ; // Months
// what comes here in case of listing year
}
I definitely agree with the solution of #FractalizeR and the addition by #elviejo , it helped me forward. But I believe I encountered some issues, and they might of help to others: (+ please correct me if I am wrong)
Important to note: both $StartDate and $StopDate are of type timestamp, not actually the date-type (1). So I changed the function parameters to $myTimestamp in the hope of not confuse others.
For example:
$StartDate = strtotime("Sept 2010");
$StopDate = time(); // current timestamp
For the functions of #elviejo:
typecasting: a simple (int) didn't work for me (PHP5), so I used intval() instead
working with % gives results ranging from 0 to 11, while months are in the range of 1 to 12 (2). So in the function GetDateFromMonths($months), we have to +1 the result
Because we add 1 to the % in the function GetDateFromMonths($months), we will have to substract 1 from the $dateAsMonths in the function GetMonthsFromDate($myTimestamp).
This gives me the following code:
function GetMonthsFromDate($myTimestamp)
{
$year = (int) date('Y',$myTimestamp);
$months = (int) date('m', $myTimestamp);
$dateAsMonths = 12*$year + $months - 1;
return $dateAsMonths;
}
function GetDateFromMonths($months)
{
$years = intval($months / 12);
$month = intval($months % 12) + 1;
$myTimestamp = strtotime("$years/$month/01"); //makes a date like 2009/12/01, and translate it to a timestamp
return $myTimestamp;
}
Started by the following for-loop:
for ($i = GetMonthsFromDate($StartDate); $i <= GetMonthsFromDate($StopDate); $i++)
{
echo(date('d M Y',GetDateFromMonths($i))."</br>");
}
Which gave the wanted result. Do my remarks make sense?
Notes:
(1) I don't even think date exists as a type in PHP, but I might be wrong.
(2) January is 1, February is 2, ... November is 11 but December is 0. This will not give the wanted result.

Categories