Date Loop isn't working correctly - php

Hi I've created a while loop for dates. I want to increase the month my 1 every time. However it isn't working and instead it increments like this :
2009/06/01
2009/07/01
2009/09/01
2009/12/01
2010/04/01
2010/09/01
which isn't correct. I dont understand why it won't increment by 1 month. Any help would be much appreciated
<?php
$startdate = "2009/06/01";
$enddate = "2009/12/31";
$start = strtotime($startdate);
$end = strtotime($enddate);
$f = 0;
$t = 6;
$d = 0;
$currentdate = $start;
while($f < $t )
{
$cur_date = date('Y/m/d', $currentdate);
$currentdate = strtotime($f . ' month', $currentdate);
echo $cur_date . "<br />";
//echo $f . "<br />";
$f = $f + 1;
}
?>

It won't work because you're not adding 1 month each time.... you're adding 1 month in the first iteration, 2 in the second, 3 in the third, etc. because you're increasing the value of $f every iteration.
$begin = new DateTime('2009-06-01');
$end = new DateTime('2009-12-31');
$end = $end->modify('+1 day');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($begin, $interval, $end);
foreach($period as $dt) {
var_dump($dt->format( "Y-m-d" ));
}

Related

How to get Months between two dates

I'm trying to get All the months between two dates.
for e.g if the user posted an article on 21-10-2012 and today date is 5-12-2017. Now i want to get all the month and Year between this period like shown below
10-2012
11-2012
01-2013
02-2014
03-2015
04-2015
05-2015
06-2015
07-2015 // and so on
.......
.......
.......
12-2017 // Till Today Date
Till Now i was only able to calculate the difference.
$article_date= date("d-m-Y", $article['date']);
$year = date("Y");
$month = date("m");
$day = date("d");
$date1 = new DateTime($article_date);
$date2 = new DateTime("$day-$month-$year");
$diff = $date1->diff($date2);
echo (($diff->format('%y') * 12) + $diff->format('%m')) . " full months difference";
How can i get all the months?
Use this code
$start = new DateTime('2012-10-21');
$start->modify('first day of this month');
$end = new DateTime('2017-12-05');
$end->modify('first day of next month');
$interval = DateInterval::createFromDateString('1 month');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("m-Y") . "<br>\n";
}
function list_months($date_from,$date_to, $return_format){
$arr_months = array();
$a = new \DateTime($date_from);
$x = new \DateTime($date_to);
$start = $a->modify('first day of this month');
$end = $x->modify('first day of next month');
$interval = \DateInterval::createFromDateString('1 month');
$period = new \DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
$arr_months[] = $dt->format($return_format);
}
return $arr_months ;
}
Example: $new_list = list_months('11-10-2012','11-10-2017', 'm-Y');

Inserting dates within an array with PHP

I am getting the starting and ending dates from a form.
I need to put within an array all the date between the former two, including themselves.
I'm using a normal for loop and, at the same time, printing the result, to verify.
Everything appear to be alright.
But when I print_r the very array, I get only a series of equal dates. Which are all the same: last date + 1.
This is the code:
$date1 = date_create("2013-03-15");
$date2 = date_create("2013-03-22");
$diff = date_diff($date1, $date2);
echo $diff->format("%R%a days");
$diffDays = $diff->days;
echo $diffDays;
$dates = array();
$addDay = $date1;
for ($i = 0; $i < $diffDays; $i++) {
$dates[$i] = $addDay;
date_add($addDay, date_interval_create_from_date_string("1 day"));
echo "array: " . $i . " : " . date_format($dates[$i], 'Y-m-d');
}
print_r($dates);
PHP code demo
<?php
$dates = array();
$datetime1 = new DateTime("2013-03-15");
$datetime2 = new DateTime("2013-03-22");
$interval = $datetime1->diff($datetime2);
$days = (int) $interval->format('%R%a');
$currentTimestamp = $datetime1->getTimestamp();
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
for ($x = 0; $x < $days; $x++)
{
$currentTimestamp = strtotime("+1 day", $currentTimestamp);
$dates[] = date("Y-m-d H:i:s", $currentTimestamp);
}
print_r($dates);
I would do it that way
$startDate = new \DateTime("2017-03-15");
$endDate = new \DateTime("2017-03-22");
$dates = [];
$stop = false;
$date = $startDate;
while(!$stop){
$dates[] = $date->format('Y-m-d'); // or $dates[] = $date->format('Y-m-d H:i:s')
$date->modify('+1 day');
if($date->getTimestamp() > $endDate->getTimestamp()){
$stop = true;
}
}
print_r($dates);

How can I calculate date weekend in php

I have a date like this
$start = strtotime('2010-01-01'); $end = strtotime('2010-01-25');
My question:
How can I calculate or count weekend from $start & $end date range..??
A more modern approach is using php's DateTime class. Below, you get an array with week numbers as keys. I added the counts of weeks and weekend days.
<?php
$begin = new DateTime('2010-01-01');
$end = new DateTime('2010-01-25');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);
$weekends = [];
foreach($daterange as $date) {
if (in_array($date->format('N'), [6,7])) {
$weekends[$date->format('W')][] = $date->format('Y-m-d');
}
}
print_r($weekends);
echo 'Number of weeks: ' . count($weekends);
echo 'Number of weekend days: ' . (count($weekends, COUNT_RECURSIVE) - count($weekends));
Note: if you're using PHP 5.3, use array() instead of block arrays [].
May be this code snippet will help:
<?php
//get current month for example
$beginday = date("Y-m-01");
$lastday = date("Y-m-t");
$nr_work_days = getWorkingDays($beginday, $lastday);
echo $nr_work_days;
function getWorkingDays($startDate, $endDate)
{
$begin = strtotime($startDate);
$end = strtotime($endDate);
if ($begin > $end) {
echo "startdate is in the future! <br />";
return 0;
} else {
$no_days = 0;
$weekends = 0;
while ($begin <= $end) {
$no_days++; // no of days in the given interval
$what_day = date("N", $begin);
if ($what_day > 5) { // 6 and 7 are weekend days
$weekends++;
};
$begin += 86400; // +1 day
};
$working_days = $no_days - $weekends;
return $working_days;
}
}
Another solution can be: (Get date range between two dates excluding weekends)
This might help maybe:
$start = strtotime('2010-01-01');
$end = strtotime('2010-01-25');
$differ = $end-$start;
$min = $differ/60;
$hrs = $min/60;
$days = $hrs/24;
$weeks = $days/7;
if(is_int($weeks))
$weeks++;
echo '<pre>';
print_r(ceil($weeks));
echo '</pre>';

How to make a for loop for some month

I want to make for loop in php pdo that will create me an json data but loop must be for an month.
I write this:
try {
for ($i=1; $i<=30; $i++) {
$temp = array();
$temp['ID'] = $i;
$output['data'][] = $temp;
}
$jsonTable = json_encode($output);
SO this return me 30 rows, for 30 days. Now I want to create a range etc. to make me a rows from 01.02.2014 to rest of month 28/29.02.2014 so February ...
How to make this possible? Some ideas?
If you can't read the manual for yourself:
$dateString = '01.02.2014';
$dt = new DateTime($dateString);
$daysInMonth = $dt->format('t');
will give you the number of days in the month specified in $dateString
One way to loop through the days in a month:
$dateString = '01.02.2014';
$startDate = new DateTime($dateString);
$period = new DateInterval('P1M');
$endDate = clone $startDate;
$endDate->add($period);
$dayPeriod = new DateInterval('P1D');
while ($startDate < $endDate) {
echo $startDate->format('Y-m-d'), PHP_EOL;
$startDate->add($dayPeriod);
}
Another way to get that list of dates for a month
$dateString = '01.02.2014';
$startDate = new DateTime($dateString);
$period = new DateInterval('P1M');
$endDate = clone $startDate;
$endDate->add($period);
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
echo $date->format("Y-m-d") . PHP_EOL;
}

How to get a day of month from "what I know"?

Need some logic here:
Need to get day of month date("d")
What I know:
$year = 2013;
$month = 10;
$week_nr_of_month = 3; // from 1 to 6 weeks in month
$day_of_week = 0; // Sunday date("w")
Thanks for logic
Result must be: 13 October
This was fun to figure out.
<?php
$year = 2013;
$month = 10;
$week_nr_of_month = 3; // from 1 to 6 weeks in month
$day_of_week = 0; // Sunday date("w")
$start = new DateTime();
$start->setDate($year, $month, '1');
$end = clone $start;
$end->modify('last day of this month');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $date) {
if ($date->format('w') == $day_of_week) {
$wom = week_of_month($date->format('Y-m-d'));
if ($week_nr_of_month == $wom) {
echo $date->format('Y-m-d');
}
}
}
function week_of_month($date) {
$dt = new DateTime($date);
$bg = clone $dt;
$bg->modify('first day of this month');
$day_of_first = $bg->format('N');
$day_of_month = $dt->format('j');
return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}
See it in action
Used this answer for inspiration to get the week number for the date.
strtotime may be of help. Can't test right now, but...
$ordinal = array("first","second","third","fourth","fifth");
$weekdays = array("monday","tuesday","wednesday","thursday","friday","saturday","sunday");
$timestamp = strtotime($year."-".$month." ".$ordinal[$week_nr_of_month]." ".$weekdays[$day_of_week]);

Categories