How to make a for loop for some month - php

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;
}

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');

Get all dates from last 30 days (datetime objects)

I am trying to get an array of datetime objects but failing miserably.
I want to take today's date, and get all dates within the last 30 days.
$today = new DateTime();
$begin = $today->sub(new DateInterval('P30D'));
$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $today);
$range = [];
foreach ($dateRange as $date) {
$range[] = $date->format('Y-m-d');
}
When I dump out $range, I get an empty array.
What am I doing wrong?
Change
$begin = $today->sub(new DateInterval('P30D'));
to
$begin = new DateTime();
$begin->sub(new DateInterval('P30D'));
the "sub" method modifies the source object, as well as outputting the object itself as the return value (really this is intended for method chaining). It doesn't just create a new object with the new date.
$begin = $today->sub(new DateInterval('P30D'));
modifies $today as well as outputting a copy which you then declare as $begin. This results in both objects having the same date, and thus there's no time interval over which to iterate.
See http://php.net/manual/en/datetime.sub.php
You need to create a separate object for your end date:
$begin = new DateTime();
$begin->sub(new DateInterval('P30D'));
$end = new DateTime();
$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $end);
$range = [];
foreach ($dateRange as $date) {
$range[] = $date->format('Y-m-d');
}
var_dump($range);
See it working at https://eval.in/867948
you overwrite $today so $today and $begin is exactly the same
$today = new DateTime();
$copy = clone $today;
$begin = $copy->sub(new DateInterval('P30D'));
$interval = new DateInterval('P1D'); // 1 Day
$dateRange = new DatePeriod($begin, $interval, $today);
$range = [];
foreach ($dateRange as $date) {
$range[] = $date->format('Y-m-d');
}
will work

Checking how many weekends are within date range

How do I check in Laravel how many Saturdays or Sundays are in given date range between $from and $to?
You can do it with plain PHP like this:
$start = new DateTime('2016-07-07');
$end = new DateTime('2016-07-27');
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($start, $interval ,$end);
$saturdays = 0;
foreach($daterange as $date){
$days = $date->format('D');
if ($days == 'Sat') {
$saturdays++;
}
}
echo $saturdays;

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

Add the correct number of days for each month

Using the following function I can display the years and months between two dates, but how can I add the correct days for each month as another array within each month? I can't just add the days manually as I need it to account for leap years etc.
function yearMonth($start_date, $end_date)
{
$begin = new DateTime( $start_date );
$end = new DateTime( $end_date);
$interval = new DateInterval('P1M'); // 1 month interval
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt )
$years[$dt->format( "Y" )][] = $dt->format( "F" );
return $years;
}
$list = yearMonth("2007-03-24", "2009-06-26");
var_dump($list);
Since nobody else answered:
function yearMonth($start_date, $end_date)
{
$begin = new DateTime( $start_date );
$end = new DateTime( $end_date);
$interval = new DateInterval('P1D'); // 1 month interval
$period = new DatePeriod($begin, $interval, $end);
$lastMonth = null;
$lastYear = null;
$aResult = array();
foreach ( $period as $dt )
{
if ($dt->format('Y') != $lastYear)
{
$lastYear = $dt->format('Y');
}
if ($dt->format('F') != $lastMonth)
{
$lastMonth = $dt->format('F');
}
if (!isset($aResult[$lastYear]))
{
$aResult[$lastYear] = array();
}
if (!isset($aResult[$lastYear][$lastMonth]))
{
$aResult[$lastYear][$lastMonth] = array();
}
$aResult[$lastYear][$lastMonth][] = $dt->format('d');
}
return $aResult;
}
On a side note I am planing to create a sort of Gantt chart style flat layout in table format of the years, months and days between dates. Do you think this is a suitable way of generating that? Or is there a better way?

Categories