Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
Generate month & year array from two dates in PHP
i have two MM/YYYY from form
ex:
$start = "2/2016";
$end = "11/2017"
i need the output in all array of months And year
like this in php
$monthArray = Array (
[0] => 2
[1] => 3
[2] => 4
[3] => 5
[4] => 6
[5] => 7
[6] => 8
[7] => 9
[8] => 10
[9] => 11
[10] => 12
[11] => 1
[12] => 2
[13] => 3
[14] => 4
[15] => 5
[16] => 6
[17] => 7
[18] => 8
[19] => 9
[20] => 10
[21] => 11
);
$yearArray = Array (
[0] => 2016
[1] => 2016
[2] => 2016
[3] => 2016
[4] => 2016
[5] => 2016
[6] => 2016
[7] => 2016
[8] => 2016
[9] => 2016
[10] => 2016
[11] => 2017
[12] => 2017
[13] => 2017
[14] => 2017
[15] => 2017
[16] => 2017
[17] => 2017
[18] => 2017
[19] => 2017
[20] => 2017
[21] => 2017
);
Function would be better. Please help. Thanks in advance
If you want to use datetime you can do:
<?php
$start = date_create_from_format("m/Y","2/2016")->modify("first day of this month");
$end = date_create_from_format("m/Y","11/2017")->modify("first day of this month");
$timespan = date_interval_create_from_date_string("1 month");
$months = [];
$years = [];
while ($start <= $end) {
$months[] = $start->format("m");
$years[] = $start->format("Y");
$start = $start->add($timespan);
}
print_r([ $months, $years ]);
Example: http://sandbox.onlinephpfunctions.com/code/8bfa8cc9481aa8a13d83f62d9c1c6c7927654842
<?php
$start = "2/2016";
$end = "11/2017";
$start = explode('/', $start);
$end = explode('/', $end);
$d1 = strtotime($start[1] . '-' . $start[0] . '-01');
$d2 = strtotime($end[1] . '-' . $end[0] . '-01');
$min_date = min($d1, $d2);
$max_date = max($d1, $d2);
$month = [];
$year = [];
while (($min_date = strtotime("+1 MONTH", $min_date)) <= $max_date) {
$month[] = date('m',$min_date);
$year[] = date('Y',$min_date);
}
print_r($month);
print_r($year);
This should work faster and use less memory than the existing answers because it doesn't rely on creation and manipulation of date objects (especially parsing strings into date objects):
/**
* Takes start and end date string in format 'mm/yyyy' along with a $months and $years
* arrays; modifies the arrays in place to add all months and years between the dates
*/
function listMonthsAndYears($start, $end, &$months, &$years) {
list($startM, $startY) = array_map('intval', explode('/',$start));
list($endM, $endY) = array_map('intval', explode('/',$end));
$m = $startM;
$y = $startY;
while($endY > $y || ($endY === $y && $endM >= $m) ){
$months[]= $m;
$years[] = $y;
$m++;
if($m > 12){ // loop to the next year
$m = 1;
$y++;
}
}
}
Usage:
$start = '2/2016';
$end = '11/2017';
listMonthsAndYears($start, $end, $months, $years);
Live demo
Related
I would like to make an array like below.
The key should be day. The value should be string weekday name.
$array = [
1 =>['mon'],
2 =>['tue'],
3 =>['wed']
];
However $day (key) can't seem to be recognised.
CODE is
//$i is the first day of a specific month. this sample is 2022-11-01
for($j = $i ; (int)date_create($j)->format('w') < 6 ; $j++){
print_r("くj");
print_r($j);
$day = date_create($j)->format('j');
print_r("day");
print_r($day);
$dailyArray = array_merge($dailyArray ,array( $day => mb_strtolower(date_create($j)->format('D'))));//
print_r("THE RESULT!!");
print_r($dailyArray);
result(November/2022) is
THE RESULT!! day4
Array
(
[0] => Tue
[1] => Wed
[2] => Thu
[3] => Fri
)
It's not the question, but it can't set (int)date_create($j)->format('w') <= 6 . How can I do the loop until sat?
The following script was based on your code basically and it will print out the result as expected, till Saturday
$dailyArray = array();
$d = 1;
while($d < 6 ){
$j = implode("-", array(2022, 11, str_pad($d, 2, '0', STR_PAD_LEFT)));
print_r("くj");
print_r($j);
$day = date_create($j)->format('j');
print_r("day");
print_r($day);
$dailyArray = array_merge($dailyArray , array( $day => strtolower(date_create($j)->format('D'))));
$d++;
}
print_r("<p>THE RESULT!!");
print_r($dailyArray);
It should print out
THE RESULT!!Array ( [0] => tue [1] => wed [2] => thu [3] => fri [4] => sat )
Actually, if (int)date_create($j)->format('w') < 6 is preferred, a shorter version could be
$d = 1;
$j = implode("-", array(2022, 11, str_pad($d, 2, '0', STR_PAD_LEFT)));
while((int)date_create($j)->format('w') < 6 ){
$j = implode("-", array(2022, 11, str_pad($d, 2, '0', STR_PAD_LEFT)));
$dailyArray[$d] = strtolower(date_create($j)->format('D'));
$d++;
}
It printed out:
THE RESULT!!Array ( [1] => tue [2] => wed [3] => thu [4] => fri [5] => sat )
I don't want to return DATE (Y-m-d).
I need to print all days until end of month from a given day independently of the month or year.
I tried both [$array as $i] - [$array as $key] and didn't work.
$myday (for example = 19)
return $days
would result:
Array
[0] => 20
[1] => 21
[2] => 22
[3] => 23
...
[31] => 31 || [30] => 30 || [28] => 28
I would need each value for $days to compare each to another field.
Didn't try to use $myday as regular number instead of treating as date. And not use strtotime, mktime....
EDITING
Need something very simple like this one:
$output = array();
for ($i=$myday+1;$i<=31 || $i<=30 || $i<=28;$i++) {
$output[] = $i;
}
But print_r won't do it, I need to return as each value to use in different if conditions
This is easily done using DateTime(), DateInterval(), DatePeriod(), and relative date formats.
$start = (new DateTime())->setDate(date('Y'), date('m'), $myday + 1);
$end = new DateTime('first day of next month');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
$days = array();
foreach($period as $date) {
$days[] = $date->format('d');
}
Results
Array
(
[0] => 20
[1] => 21
[2] => 22
[3] => 23
[4] => 24
[5] => 25
[6] => 26
[7] => 27
[8] => 28
[9] => 29
[10] => 30
[11] => 31
)
Demo
$start_date = "2013-05-01";
$last_date = "2013-08-30";
How can I get dates of tuesdays and thursdays between these two dates?
<?php
$start = new DateTime('2013-05-01');
$end = new DateTime('2013-08-30');
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
if ($dt->format("N") == 2 || $dt->format("N") == 4) {
echo $dt->format("l Y-m-d") . "<br>\n";
}
}
See it in action
What this code does:
Creates a starting date object using DateTime.
Creates a starting date object using DateTime.
Creates a DateInterval object to represent our interval of time to iterate through. In this case 1 day.
Creates a DatePeriod object to manage these objects.
Using DatePeriod, it iterates through the date starting with the starting date and ending at the end date. We use DateTime::format() with the N parameter to get the day number of the week. If the day number of the week is 2 (Tuesday) or 4 (Thursday) echo out it's value.
Some PHP-Fu
$start_date = '2013-05-01';
$last_date = '2013-08-30';
$dates = range(strtotime($start_date), strtotime($last_date),86400);
$days = array('tuesday' => array(), 'thursday' => array());
array_map(function($v)use(&$days){
if(date('D', $v) == 'Tue'){
$days['tuesday'][] = date('Y-m-d', $v);
}elseif(date('D', $v) == 'Thu'){
$days['thursday'][] = date('Y-m-d', $v);
}
}, $dates); // Requires PHP 5.3+
print_r($days);
Output
Array
(
[tuesday] => Array
(
[0] => 2013-05-07
[1] => 2013-05-14
[2] => 2013-05-21
[3] => 2013-05-28
[4] => 2013-06-04
[5] => 2013-06-11
[6] => 2013-06-18
[7] => 2013-06-25
[8] => 2013-07-02
[9] => 2013-07-09
[10] => 2013-07-16
[11] => 2013-07-23
[12] => 2013-07-30
[13] => 2013-08-06
[14] => 2013-08-13
[15] => 2013-08-20
[16] => 2013-08-27
)
[thursday] => Array
(
[0] => 2013-05-02
[1] => 2013-05-09
[2] => 2013-05-16
[3] => 2013-05-23
[4] => 2013-05-30
[5] => 2013-06-06
[6] => 2013-06-13
[7] => 2013-06-20
[8] => 2013-06-27
[9] => 2013-07-04
[10] => 2013-07-11
[11] => 2013-07-18
[12] => 2013-07-25
[13] => 2013-08-01
[14] => 2013-08-08
[15] => 2013-08-15
[16] => 2013-08-22
[17] => 2013-08-29
)
)
Online demo
$start_date = strtotime("2013-05-01");
$last_date = strtotime("2013-08-30");
while ($start_date <= $last_date) {
$start_date = strtotime('+1 day', $start_date);
if (date('N',$start_date) == 2 || date('N',$start_date) == 4){
echo date('Y-m-d', $start_date).PHP_EOL;
}
}
<?php echo date('Y-m-d', strtotime('next thursday', strtotime($start_date)));
Also for tuesday ofcourse
Please use the following function for your solution,
function daycount($day, $startdate, $lastdate, $counter=0)
{
if($startdate >= $lastdate)
{
return $counter;
}
else
{
return daycount($day, strtotime("next ".$day, $startdate), ++$counter);
}
}
$start_date = "2013-05-01";
$last_date = "2013-08-30";
echo "Tuesday Count - ".daycount("tuesday", strtotime($start_date), strtotime($last_date));
echo "<br/>";
echo "Thursday Count - ".daycount("thursday", strtotime($start_date), strtotime($last_date));
Try with this
$startDate = strtotime($start_date);
$endDate = strtotime($last_date);
while ($startDate < $endDate) {
echo date('Y-m-d', $startDate ). "\n";
// Give the condition to find last Tuesday
$startDate = strtotime( 'next Tuesday', $startDate );
}
With DateTime:
$start_date = "2013-05-01";
$last_date = "2013-08-30";
$start = new DateTime($start_date);
$clone = clone $start;
$start->modify('next thursday');
$thursday=$start->format('Y-m-d');
$clone->modify('next tuesday');
$tuesday=$clone->format('Y-m-d');
echo $thursday; //2013-05-02
echo $tuesday; //2013-05-07
We need to objects because if in interval tuesday is before thursday we will have next tuesday. But you can modify little code to use one object.
With the help of few php date functions this can be solved easily..
<?php
// Create the from and to date
$start_date = strtotime("2013-05-01");
$last_date = strtotime("2013-08-30");
// Get the time interval to get the tue and Thurs days
$no_of_days = ($last_date - $start_date) / 86400; //the diff will be in timestamp hence dividing by timestamp for one day = 86400
$get_tue_thu_days = array();
// Loop upto the $no_of_days
for($i = 0; $i < $no_of_days; $i++) {
$temp = date("D", $start_date);
if($temp == "Tue" || $temp == "Thu") {
$get_tue_thu_days[] = date("D/M/Y", $start_date); //formating date in Thu/May/2013 formate.
}
$start_date += 86400;
}
print_r($get_tue_thu_days);
if you have a reference date which you know is a tuesday/thursday you can find days which are a multiple of 7 days from your reference date, these days will always be the same day of the week.
This question already has answers here:
Display all the week numbers between two dates in PHP [duplicate]
(3 answers)
Closed 8 years ago.
Given a start and end date, I need to generate an array with year and week values.
For example:
Start Date: 2013-01-01
End Date: 2013-02-23
Generated Array:
Array ( [0] => Array ( [week] => 01 [year] => 2013 )
[1] => Array ( [week] => 02 [year] => 2013 )
[2] => Array ( [week] => 03 [year] => 2013 )
[3] => Array ( [week] => 04 [year] => 2013 )
[4] => Array ( [week] => 05 [year] => 2013 )
[5] => Array ( [week] => 06 [year] => 2013 )
[6] => Array ( [week] => 07 [year] => 2013 )
[7] => Array ( [week] => 08 [year] => 2013 ) )
Here is the code I'm using to generate this:
public static function getYearWeekRange($startdate, $enddate) {
$array = array();
$starttime = strtotime($startdate);
$endtime = strtotime($enddate);
while ($starttime <= $endtime) {
$year = date('Y', $starttime);
$week = date('W', $starttime);
$array[] = array('week' => $week, 'year' => $year);
$starttime = strtotime('+1 week', $starttime);
}
return $array;
}
My problem is that when I generate certain date ranges, I don't get the correct year value at the start of the 2013 year. For example:
Start Date: 2012-01-01
End Date: 2013-02-23
In this case, where it should have an subarray with year = 2013 and week = 01, it actually has it's year value equal to 2012.
If I were to switch the start date to 2013-01-05 for example, then there is no problem.
Can anyone offer a solution that would guarantee that my year and week values are always correct?
I was able to fix my problem using the following:
public static function getWeekRange($startdate, $enddate) {
$array = array();
$p = new DatePeriod(
new DateTime($startdate),
new DateInterval('P1W'),
new DateTime($enddate)
);
foreach ($p as $w) {
$array[] = array('year' => $w->format('o'), 'week' => $w->format('W'));
}
return $array;
}
I want to build a movie timetable. I have $array1 containing the movie titles and airing dates and times:
array =
0: array =
Title: string = American Beauty
Date: string = 25/09/2012
Time: string = 15:00 - 16:20
1: array =
Title: string = The Godfather
Date: string = 25/09/2012
Time: string = 16:20 - 18:20
2: array =
Title: string = Pulp Fiction
Date: string = 26/09/2012
Time: string = 15:00 - 16:20
And I have $array2 containing the days of the month grouped by Mondays, Tuesday s, Wednesday s, Thursday s and Fridays (no movies during the weekend)
Array
(
[1] => Array
(
[0] => 3
[1] => 10
[2] => 17
[3] => 24
[4] =>
)
[2] => Array
(
[0] => 4
[1] => 11
[2] => 18
[3] => 25
[4] =>
)
[3] => Array
(
[0] => 5
[1] => 12
[2] => 19
[3] => 26
[4] =>
)
[4] => Array
(
[0] => 6
[1] => 13
[2] => 20
[3] => 27
[4] =>
)
[5] => Array
(
[0] => 7
[1] => 14
[2] => 21
[3] => 28
[4] =>
)
)
I need to intersect these two arrays so I can print under day 25 the movie “American Beauty” also under day 25 “The Godfather” and under day 26 “Pulp Fiction”.
Meaning I need to print:
SEPTEMBER 2012
Monday Tuesday Wednesday ....
3 4 5
10 11 12
17 18 19
24 25 26
15:00-16:20 American Beauty 15:00-16:20 Pulp Fiction
16:20-18:20 The Godfather
My tries so far:
foreach( $array1 as $key => $value )
{
$theTime = $value['Time'];
$theTime = explode("/", $theTime );
$days[] = $theTime [0];
$months[] = $theTime [1];
}
So I have all the airing days in array $days but from here I don’t know how to follow or even if this approach is the correct one.
Here's how I get $array2:
$month = 9;
$year = 2012;
for ($i = 1; $i <= 31; $i++)
{
$timestamp = mktime(0, 0, 0, $month , $i, $year);
if (date("n", $timestamp) == $month )
{
$day = date("N", $timestamp);
// Monday 1 to Friday 5
if ($day == 1 OR $day <= 5) {
$array2[$day][] = date("j", $timestamp);
}
}
}
Please help, I’m stuck.
Thanks very much
Ok you will iterate over $array1 and parse the date of the movie.
Then, you will look inside array2 if your day is there
foreach($array1 as $movie){
$movieDate = new DateTime($movie);
//as you indexed $array2 with monday = 1 -> friday = 5 you can use the "w" format
if(isset($array2[$movieDate->format("w"))){
$array[$movieDate->format("j")][] = $movie;
}
}
I made some mutation in your output array, it becomes :
SEPTEMBER 2012
Monday Tuesday Wednesday ....
3=>[] 4 =>[] 5=>[]
10=>[] 11 =>[] 12=>[]
17=>[] 18 =>[] 19=>[]
24 =>[] 25=>[ 26 =>[
15:00-16:20 American Beauty, 15:00-16:20 Pulp Fiction]
16:20-18:20 The Godfather]