I would like to ask why December is skipping when you try to run the code below? Can somebody help me or explain to me why december is not included in looping? thanks
$date = "2013-03-31";
$d1 = explode("-",$date);
$i = 0;
while ($i < 12)
{
$j = $d1[2];
if(cal_days_in_month(CAL_GREGORIAN, $d1[1], $d1[0]) < $d1[2])
$j = cal_days_in_month(CAL_GREGORIAN, $d1[1], $d1[0]) ;
echo $d1[0]."-".$d1[1]."-".$j."<br>";
$d1[1]++;
if($d1[1] == 12)
{
$d1[0]++;
$d1[1] = 1;
}
$i++;
if($d1[1] < 10)
$d1[1]="0".$d1[1];
}
Result:
2013-03-31
2013-04-30
2013-05-31
2013-06-30
2013-07-31
2013-08-31
2013-09-30
2013-10-31
2013-11-30
2014-01-31
2014-02-28
2014-03-31
Missing :
2013-12-31
here is my fixed version:
<?php
$date = "2013-03-31";
$d1 = explode("-",$date);
$i = 0;
while ( $i<=12 ){
$j = $d1[2];
if(cal_days_in_month(CAL_GREGORIAN,$d1[1],$d1[0])<$d1[2])
$j = cal_days_in_month(CAL_GREGORIAN,$d1[1],$d1[0]);
echo $d1[0]."-".$d1[1]."-".$j."<br>";
if($d1[1]==12){
$d1[0]++;
$d1[1] = 1;
}else{
$d1[1]++;
}
$i++;
if($d1[1]<10)
$d1[1] = "0".$d1[1];
}
basically you were dealing with the role over from 12 to 1 incorrectly.
Related
I saw this question:
how to get the previous 3 months in php
My question is.. How do i output from a custom month.
I want to start from Mar 2018 (or any M Y user inputs) and it should output the next 3 (or any number user inputs) months.
Ex: Mar, Apr, May
The code below is from current month and year.
// current month: Aug 2018
for ($i = 0; $i <= 2; $i++){
$x = strtotime("$i month");
echo $dte = date('M Y', $x);
echo '<br>';
}
And the output is
Aug 2018
Sep 2018
Oct 2018
You could use the DateTime class and increment using a DateInterval object:
// Assuming these are the user inputs
$month = 11;
$year = 2015;
// We create a new object with year and month format
$date = DateTime::createFromFormat('Y m', $year . ' ' . $month);
for ($i = 0; $i <= 2; $i++){
// Output the month and year
echo $date->format('m Y') . '<br>';
// Add 1 month to the date
$date->add(new DateInterval('P1M'));
}
Output:
11 2015
12 2015
01 2016
Documentation:
DateTime::createFromFormat
DateTime::format
DateTime::add
Change it to this as below it will give you as expected see the below code
// current month: Aug 2018
$effective_date = "MAR 2018";
for ($i = 0; $i <= 2; $i++){
$x = strtotime("$i month",strtotime($effective_date));
echo $dte = date('M Y', $x);
echo '<br>';
}
This may be also helpful:
<?php
$month = 11;
$year = 2017;
$count = 15;
for ($i = 1; $i <= $count; $i++) {
$month++;
if ($month > 12) {
$month = 1;
$year++;
}
$x = DateTime::createFromFormat('Y-m', $year.'-'.$month);
echo $x->format('m-Y');
echo '<br>';
}
?>
Output:
12-2017
01-2018
02-2018
03-2018
04-2018
05-2018
06-2018
07-2018
08-2018
09-2018
10-2018
11-2018
12-2018
01-2019
02-2019
Try this code for add nth Days, Months and Years
$n = 2;
for ($i = 0; $i <= $n; $i++){
$d = strtotime("$i days");
$x = strtotime("$i month");
$y = strtotime("$i year");
echo "Dates : ".$dates = date('d M Y', "+$d days");
echo "<br>";
echo "Months : ".$months = date('M Y', "+$x months");
echo '<br>';
echo "Years : ".$years = date('Y', "+$y years");
echo '<br>';
}
You can generate the date with strtotime() function
Check this phpfiddle
<?php
$currMonth = 11;
$currYear = 2017;
$count = 15;
$currentYear = date('M Y',strtotime($currYear.'-'.$currMonth));
echo $currentYear.'<br>';
for ($i = 1; $i < $count; $i++) {
$currMonth++;
if ($currMonth > 12) {
$currMonth = 1;
$currYear++;
}
$newMonthandYear = date('M Y',strtotime($currYear.'-'.$currMonth));
echo $newMonthandYear.'<br>';
}
?>
<?php
$year = date('Y');
//start at march
$startMonth = 7;
//go forwards 2 months
$stepForwards = 22;
for ($i = $startMonth; $i <= $stepForwards; $i++){
if($i > 12 ) {
$month = $i % 12 == 0 ? 12 : $i % 12;
}
else {
$month = $i;
}
echo date("M Y", strtotime(date($year.'-'.$month.'-1'))) . "<br/>";
if($month == 12) {
$year++;
echo "<br/>";
}
}
What I can do if would like start my January month since 2016-01-01 not 2016-01-02.
https://3v4l.org/uRRfU
function countDaysForChoosenYears(int $year):int
{
$att = [];
for ($i = 1; $i <= 12; $i++) {
$att[] = cal_days_in_month(CAL_GREGORIAN, $i, $year);
}
$att = array_sum($att);
return $att;
}
$YearMonthDayStructure = [];
$Date = new DateTime('2016-01-01');
for ($i = 1; $i <= countDaysForChoosenYears(2016); $i++) {
$monthName = $Date->format('F');
$yearNumber = $Date->format('Y');
$YearMonthDayStructure[$yearNumber][$monthName][$Date->format('d')] = $Date->add(new DateInterval('P1D'))->format('Y-m-d');
}
print_r($YearMonthDayStructure);
The very first time you enter the loop you are adding P1D to the date. So your first date ends up being 2 Jan because you added P1D to 1 Jan on that line with the $Date->add. It's not like $x++ where the '++' happens after you use the variable. It performs the add and then gives the result, with the added P1D, to the $YearMonthDayStructure value.
when start date ex:6/1/2016 and
end date ex : 8/1/2016
It is the process by computational days, so the process is the result of 3 days
6/1/2016 day
7/1/2016 day
8/1/2016 day
This is wrong .
Must be 6/1/2016 to 7/1/2016 day and 7/1/2016 to 8/1/2016 day
so the sum 2 day not 3 days
$start_date = strtotime($date_from);
$end_date = strtotime($date_to);
$datetime1 = date_create($date_from);
$datetime2 = date_create($date_to);
$interval = date_diff($datetime1, $datetime2);
$cs_booking_days = $interval->days;
// Loop between timestamps, 24 hours at a time
$total_price = '';
$adult_price = 0;
$pricings = get_option('cs_price_options');
$cs_offers_options = get_option("cs_offers_options");
$pricings_array = $pricings[$post_id];
if (isset($pricings[$post_id]['cs_plan_days'])) {
$cs_sp_days = $pricings[$post_id]['cs_plan_days'];
}
$pricing_data = array();
$brk_counter = 0;
$total_orignal = 0;
$price['total_price'] = 0;
$flag = false;
for ($i = $start_date; $i <= $end_date; $i = $i + 86400) {
$total_days++;
$brk_counter++;
$thisDate = date('Y-m-d', $i); // 2010-05-01, 2010-05-02, etc
$day = strtolower(date('D', strtotime($thisDate)));
$adult_price = $pricings_array['cs_pricing_branches']['adult_' . $day . '_price'][0];
$adult_temp_price = $adult_price != '' ? $adult_price : 0;
$adult_price = $adult_temp_price;
$to_check_date = strtotime(date('Y-m-d', $i));
<?php
// your code goes here
$startTimeStamp = strtotime("2016/01/06");
$endTimeStamp = strtotime("2016/01/08");
$timeDiff = abs($endTimeStamp - $startTimeStamp);
$numberDays = $timeDiff/86400; // 86400 seconds in one day
// and you might want to convert to integer
$numberDays = intval($numberDays);
echo $numberDays;
http://ideone.com/8miDiP
Back to your code => Replace
for ($i = $start_date; $i <= $end_date; $i = $i + 86400) {
this
for ($i = $start_date; $i < $end_date; $i = $i + 86400) {
<= is problem, type <
EXPLANATION
06.01 - 08.01
First loop:
$i = 06.01 and <= 08.01
Second loop:
$i = 07.01 and <= 08.01
Third loop:
$i = 08.01 and <= 08.01 - STILL TRUE, so SUM = 3 days
After change
First loop:
$i = 06.01 and < 08.01
Second loop:
$i = 07.01 and < 08.01
Third loop:
$i = 08.01 and < 08.01 - NOW FALSE, so SUM = 2 days
I want a PHP for loop that goes to certain number say "23" and again starts from "0".
Actually I want for the listing of time in 24 hours format and suppose a case is: I have to show time from 9 AM to 2 AM (i.e 9,10,11,12,13,14,...........23,0,1,2)
$i= range(0,23);//it doest work as it creates an array containing a range of elements
$start_time = 9;
$end_time = 2;
for ($i = $start_time ; $i<= $end_time ; $i++)
{
echo $i;
}
Please suggest a way.
Since your use-case mentions time-sensitive information you might be best off learning to use the date and strtotime functions (or the DateTime classes):
$time = strtotime('2013-09-14 02:00');
$endTime = strtotime('2013-09-15 09:00');
while ($time <= $endTime) {
echo date('Y-m-d H:i:s', $time)."\n";
$time = strtotime('+1 hour', $time);
}
// 2013-09-14 02:00:00
// 2013-09-14 03:00:00
// 2013-09-14 04:00:00
// 2013-09-14 05:00:00
// etc.
$start_time = 9;
$end_time = 2;
$end_time += ($end_time < $start_time) ? 24 : 0;
for ($i = $start_time; $i<= $end_time; $i++) {
echo ($i % 24);
}
Reason, the line $end_time += ($end_time < $start_time) ? 24 : 0; checks to see if the end time is less than the start time (which we assume means the next day), and if it is, it adds 24 hours to it. The line $i %24 is the modulus operator which will divide the number and give the remainder, so if it's 25, it will give you 1 back. Note that all hours being worked with will need to be in 24 hour format to use this method.
You can use the modulo to deduct 24 from numbers when they're greater than 23.
$start_time = 9;
$end_time = 2;
for( $i = $start_time; $i % 24 != $end_time; $i++ )
{
echo $i % 24;
}
Note that you need to be careful with this; if $end_time is greater than 23 it will be stuck in an infinite loop.
Try this its working
<?php
$i= range(0,23);//it doest work as it creates an array containing a range of elements
$start_time = 9;
$end_time = 2;
$max_value=23;
if($start_time>=$end_time)
{
for ($i = $start_time ; $i<= $max_value; $i++)
{
echo $i;
}
for($i=0; $i<=$end_time; $i++)
{
echo $i;
}
}
else
{
for ($i = $start_time ; $i<= $max_value; $i++)
{
echo $i;
}
}
?>
Again late to Answer , Try this
<?php
$start_time = 20;
$end_time = 10;
$maxTime=23;
$minTime=0;
for ($i = $minTime ; $i<=$maxTime - abs($start_time-$end_time) ; $i++)
{
$validTime= $start_time + ($i % $maxTime);
$validTime= $validTime>$maxTime?$validTime-$maxTime:$validTime;
echo $validTime;
}
?>
Check this out. Hope this helps
$start_time = 9;
$end_time = 2;
$flag = 1;
while($flag) [
echo $start_time . "<br>";
$start_time++;
if ($start_time == 23) { $start_time = 0; }
if ($start_time == $end_time) {
$flag = 0;
}
}
Does it have to be a for loop?
You can try this
function hours($range, $recurse = true, $end = array())
{
foreach($range as $time)
{
echo $time . "\n";
}
if($recurse && sizeof($end) > 0)
{
$range = range($end['start'], $end['end']);
hours($range, false);
}
}
$range = range(9,23);
$end = array('start' => 0, 'end' => 2);
hours($range, true, $end);
Maybe better to use date:
$hours = 8;
for ($i=1; $i<=8; $i++){
echo 'TIME1 = '.date("Y-m-d H:i:s",mktime (20+$i,15,18,06,05,2013)).'<br>';
}
or better DateTime class:
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2013-06-05 20:15:18');
$hours = 8;
for ($i=0; $i<8; $i++){
$date->add(new DateInterval('PT1H'));
echo 'TIME2 = '.$date->format('Y-m-d H:i:s').'<br>';
}
Thanks everybody for your help, using your ideas I got my work done.
Here is the code that actually worked.
$start_time = some_dynamic_value;
$end_time = some_dynamic_value;
$i= $start_time;
$flag = false;
if($start_time > $end_time)
$flag = true;
while ($i <= $end_time || $flag)
{
echo $i;
if($i == 24)
{
$i= 0;
$flag = false;
}
$i++;
}
I'm struggling with how to build the following:
result I need:
$months = array();
$months
(
month[0] = '2011-10-1'
month[1] = '2011-11-1'
month[2] = '2011-12-1'
month[3] = '2012-1-1'
)
from the following variables:
$date = '2011-10-1';
$numberOfMonths = 4;
Any help would be appreciated.
Thanks, guys... all of these solutions work. I accepted the one that works best for my usage.
You can do it using a simple loop and strtotime():
$date = '2011-10-1';
$numberOfMonths = 4;
$current = strtotime($date);
$months = array();
for ($i = 0; $i < $numberOfMonths; $i++) {
$months[$i] = date('Y-n-j', $current);
$current = strtotime('+1 month', $current);
}
$date = DateTime::createFromFormat('Y-m-j', '2011-10-1');
$months = array();
for ($m = 0; $m < $numberOfMonths; $m++) {
$next = $date->add(new DateInterval("P{$m}M"));
$months[] = $next->format('Y-m-j');
}
<?php
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')));
}
print_r($months);
}
getNextMonths('2011-10-1', 4);
Working demo
You could use split on date and then a for loop over the month. The trick is to use something like
$newMonth = ($month + $i) % 12 + 1;
(% is called modulo and does exactly what you want.)