Get all occurrence of specific day in a month - php

Suppose i have a month June 2014. Now i want to get dates of all Mondays in June month.
like Monday is coming on following days so answer will be like following
2014-06-02
2014-06-09
2014-06-16
2014-06-23
2014-06-30
please do not give be static solution only for June. I need dynamic solution for every month and purely in PHP.

Try this -
<?php
$startDate = "2014-06-01";
$endDate = "2014-06-30";
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
for($i = strtotime('Monday', $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
echo date('l Y-m-d', $i).PHP_EOL;
DEMO:
http://3v4l.org/n4ULA

Try to create an array with all your date with day on key (with variable $day and $date):
$array = array("Monday" => "2014-06-02", "Tuesday" => "2014-06-03", "Wednesday" => "2014-06-04");
You create a loop to reach all the result :
foreach($array as $key => $value {
if($key == "Monday")
echo $value;
}

Using the above, I created this so you can use variables to define the month, year, and selected weekday.
$month = "6";
$year = "2022";
$weekday = "Tuesday";
$d=cal_days_in_month(CAL_GREGORIAN,$month,$year);
$first_date_of_month = $year."-".$month."-01";
$last_date_of_month = $year."-".$month."-".$d;
$startDate = strtotime($first_date_of_month);
$endDate = strtotime($last_date_of_month);
for($i = strtotime($weekday, $startDate); $i <= $endDate; $i = strtotime('+1 week', $i))
echo "<br />". date('l Y-m-d', $i).PHP_EOL;

Related

How to get next 10 sundays by giving start date.?

How can i get next 10 Sundays by giving just current data,
Following is my code but it is between date ranges i just want to give start date and get next 10 Sundays from start date(Without end date).
$allweeks=array();
$startDate = date('Y-m-d');
$date = new DateTime($startDate);
$interval = new DateInterval('P2M');
$date->add($interval);
$endDate=$date->format('Y-m-d');
for ($i = strtotime($startDate); $i <= strtotime($endDate); $i = strtotime('+1 day', $i)) {
if (date('N', $i) == 1)
$allweeks[]= date('n-j', $i);
}
foreach($allweeks as $wks)
{
$weeks=explode('-', $wks);
echo '=Week of '.$weeks[0]."/".$weeks[1];
}
you can use DateTime class or strtotime function for same:
Have a look on below code:
Using DateTime Class
$date = '2016-04-05';
$date = new DateTime($date);
// Modify the date it contains
for($i =0; $i < 10; $i++){
$date->modify('next sunday');
// Output
echo $date->format('l : Y-m-d');
echo '<br />';
}
Using strtotime function
$date = '2016-04-05';
// Modify the date it contains
for($i =0; $i < 10; $i++){
$date = date('Y-m-d', strtotime('next sunday', strtotime($date)));
echo date('l : Y-m-d', strtotime($date));
echo '<br />';
}
output
Sunday : 2016-04-10
Sunday : 2016-04-17
Sunday : 2016-04-24
Sunday : 2016-05-01
Sunday : 2016-05-08
Sunday : 2016-05-15
Sunday : 2016-05-22
Sunday : 2016-05-29
Sunday : 2016-06-05
Sunday : 2016-06-12

How to find specific day from years given PHP?

I am looking on how to get specific day from time given :
let's say I have 2 dates : 1 Jan 2016 until 1 Jan 2017, I will need to know how many Mondays are there, or Tuesdays or any days that I select on the input I gave.
Is there any best way to achieve this ?
UPDATED ANSWER
<?php
$count = 0;
$days = array("Monday", "Friday");
foreach ($days as $day) {
$startDate = '1 Jan 2016';
$endDate = '1 Jan 2017';
$endDate = strtotime($endDate);
$i = '';
for ($i = strtotime($day, strtotime($startDate)); $i <= $endDate; $i = strtotime('+1 week', $i)) {
echo date('l Y-m-d', $i) . '<br>';
$count++;
}
}
echo $count;
Try modify this example:
<?php
//http://php.net/manual/en/class.dateperiod.php#109846
$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
foreach($daterange as $date){
//HERE ADD YOUR CONDITIONS...
echo $date->format("Ymd") . "<br>";
}
?>
You can reviewer this solution PHP create range of dates
get all days and loop through them all, get the first Monday after the start date and then iterate 7 days at a time:
$endDate = strtotime($endDate);
for($i = strtotime('Monday', strtotime($startDate)); $i <= $endDate; $i =strtotime('+1 week', $i))
echo date('l Y-m-d', $i);

PHP: DatePeriod with last day of month

I'd like to work with PHP DateInterval to iterate through months:
$from = new DateTime();
$from->setDate(2014, 1, 31);
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
I'd expect it to returns 31 January, 28 February (as the DateInterval is 1 month), but it actually returns 31 January, 3 March, 3 of April... hence skipping February.
Is there any way to do this simply?
Thanks!
EDIT : as a refernece, here is a solution that seems to cover most use cases:
$date = new DateTime('2014-01-31');
$start = $date->format('n');
for ($i = 0; $i < 28; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > ($start % 12) && $start !== 12) {
$current->modify('last day of last month');
}
$start++;
echo $current->format('Y-m-d').PHP_EOL;
}
You can use DateTime::modify():
$date = new DateTime('last day of january');
echo $date->format('Y-m-d').PHP_EOL;
for ($i = 1; $i < 12; $i++) {
$date->modify('last day of next month');
echo $date->format('Y-m-d').PHP_EOL;
}
EDIT: I think I didn't understand your question clearly. Here is a new version:
$date = new DateTime('2014-01-31');
for ($i = 0; $i < 12; $i++) {
$current = clone $date;
$current->modify('+'.$i.' month');
if ($current->format('n') > $i + 1) {
$current->modify('last day of last month');
}
echo $current->format('Y-m-d').PHP_EOL;
}
The issue is cause by the variance between the last day in each of the months within the range. ie. February ending on 28 instead of 31 and the addition of 1 month from the last day 2014-01-31 + 1 month = 2014-03-03 https://3v4l.org/Y42QJ
To resolve the issue with DatePeriod and simplify it a bit, adjust the initial date by resetting the specified date to the first day of the specified month, by using first day of this month.
Then during iteration, you can modify the date period date by using last day of this month to retrieve the bounds of the currently iterated month.
Example: https://3v4l.org/889mB
$from = new DateTime('2014-01-31');
$from->modify('first day of this month'); //2014-01-01
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
echo $date->modify('last day of this month')->format('Y-m-d');
}
Result:
2014-01-31
2014-02-28
2014-03-31
2014-04-30
2014-05-31
2014-06-30
2014-07-31
2014-08-31
2014-09-30
2014-10-31
2014-11-30
2014-12-31
2015-01-31
Then to expand on this approach, in order to retrieve the desired day from the specified date, such as the 29th. You can extract the specified day and adjust the currently iterated month as needed when the day is out of bounds for that month.
Example: https://3v4l.org/SlEJc
$from = new DateTime('2014-01-29');
$day = $from->format('j');
$from->modify('first day of this month'); //2014-01-01
$period = new DatePeriod($from, new DateInterval('P1M'), 12);
foreach ($period as $date) {
$lastDay = clone $date;
$lastDay->modify('last day of this month');
$date->setDate($date->format('Y'), $date->format('n'), $day);
if ($date > $lastDay) {
$date = $lastDay;
}
echo $date->format('Y-m-d');
}
Result:
2014-01-29
2014-02-28 #notice the last day of february is used
2014-03-29
2014-04-29
2014-05-29
2014-06-29
2014-07-29
2014-08-29
2014-09-29
2014-10-29
2014-11-29
2014-12-29
2015-01-29
You may try like this:
$date = new DateTime();
$lastDayOfMonth = $date->modify(
sprintf('+%d days', $date->format('t') - $date->format('j'))
);
I would do it probably like this
$max = array (
31,28,31,30,31,30,31,31,30,31,30,31
); //days in month
$month = 1;
$year = 2014;
$day = 31;
$iterate = 12;
$dates = array();
for ($i = 0;$i < $iterate;$i++) {
$tmp_month = ($month + $i) % 12;
$tmp_year = $year + floor($month+$i)/12;
$tmp_day = min($day, $max[$tmp_month]);
$tmp = new DateTime();
$tmp->setDate($tmp_year, $tmp_month + 1, $tmp_day);
$dates[] = $tmp;
}
var_dump($dates);
This keeps to the same day each month if possible

php - for loop for each month of year

I want a loop that checks the current month, 12 months in the future and 4 months in the past.
For example: Today is 1st August 08. My loop should go through April, May, June, July, August, September, October, November, December, January, February, March, April, May, June, July, and August.
I have tried strotime but I don't know how I can loop 4 months back and 12 months in the future.
Here is my code
$i = 1;
$month = strtotime('2013-08-01');
while($i <= 12) {
$month_name = date('F', $month);
echo $month_name;
echo "<br>";
$month = strtotime('+1 month', $month);
$i++;
I think Yoshi was almost there with his answer, but using DatePeriod with DateTime is more consistent and makes for more readable code IMHO:-
$oneMonth = new \DateInterval('P1M');
$startDate = \DateTime::createFromFormat('d H:i:s', '1 00:00:00')->sub(new \DateInterval('P4M'));
$period = new \DatePeriod($startDate, $oneMonth, 16);
foreach($period as $date){
//$date is an instance of \DateTime. I'm just var_dumping it for illustration
var_dump($date);
}
See it working
This can be quite tricky, here's how I would do it:
$month = date("n", "2013-08-01") - 1; // -1 to get 0-11 so we can do modulo
// since you want to go back 4 you can't just do $month - 4, use module trick:
$start_month = $month + 8 % 12;
// +8 % 12 is the same is -4 but without negative value issues
// 2 gives you: 2+8%12 = 10 and not -2
for ($i = 0; $i < 16; $i += 1) {
$cur_month = ($start_month + $i) % 12 + 1; // +1 to get 1-12 range back
$month_name = date('F Y', strtotime($cur_month . " months"));
var_dump(month_name);
}
something like this?:
$start = -4;
$end = 12;
for($i=$start; $i<=$end;$i++) {
$month_name = date('F Y', strtotime("$i months"));
echo $month_name;
echo "<br>";
}
Your code, just slightly modified.
date_default_timezone_set('UTC');
$i = 1;
$month = strtotime('-4 month');
while($i <= 16) {
$month_name = date('F', $month);
echo $month_name;
echo "<br>";
$month = strtotime('+1 month', $month);
$i++;
}
Simplest solution:
for($i=-4; $i<=12; $i++) {
echo date("F",strtotime( ($i > 0) ? "+$i months" : "$i months") )."\n";
}
Explanation:
The loop starts at -4 and goes all the way upto 12 (total 17, including 0). The ternary statement inside strtotime() simply checks if $i is positive, and if it is, a + is inserted so that we'll get the results for strtotime("+1 months") and similar.
Ta-da!
Using DateTime is the easiest and more readable way.
I would do it like this:
$from = new DateTime('-4 month');
$to = new DateTime('+12 month');
while($from < $to){
echo $from->modify('+1 month')->format('F');
}

How to get all fridays from current month

I have a problem,
$fridays = array();
$fridays[0] = date('Y-m-d', strtotime('first friday of this month'));
$fridays[1] = date('Y-m-d', strtotime('second friday of this month'));
$fridays[2] = date('Y-m-d', strtotime('third friday of this month'));
$fridays[3] = date('Y-m-d', strtotime('fourth friday of this month'));
$fridays[4] = date('Y-m-d', strtotime('fifth friday of this month'));
but there is no fifth friday. Some months have fifth fridays. How to check and not set the last item array?
$fifth = strtotime('fifth friday of this month');
if (date('m') === date('m', $fifth)) {
$fridays[4] = date('Y-m-d', $fifth);
}
You can do this using the PHP date function. Get the month you want in $timestamp and then do something like this:
<?php
function fridays_get($month, $stop_if_today = true) {
$timestamp_now = time();
for($a = 1; $a < 32; $a++) {
$day = strlen($a) == 1 ? "0".$a : $a;
$timestamp = strtotime($month . "-$day");
$day_code = date("w", $timestamp);
if($timestamp > $timestamp_now)
break;
if($day_code == 5)
#$fridays++;
}
return $fridays;
}
echo fridays_get('2011-02');
You can find a similar post about this: In PHP, how to know how many mondays have passed in this month uptil today?
I have a function to count fridays in a month to my very own application.... it could be helpful for someone.
function countFridays($month,$year){
$ts=strtotime('first friday of '.$year.'-'.$month.'-01');
$ls=strtotime('last day of '.$year.'-'.$month.'-01');
$fridays=array(date('Y-m-d', $ts));
while(($ts=strtotime('+1 week', $ts))<=$ls){
$fridays[]=date('Y-m-d', $ts);
}return $fridays;
}
I'm not on a machine that I could test this but what about something along the lines of....
if(date('Y-m-d', strtotime('fifth friday of this month')) > ""){
$fridays[4] = date('Y-m-d', strtotime('fifth friday of this month'));
}
The link below does exactly the same thing and will cover exactly what you are wanting todo without clunky if statements like above..
VERY Similar reading: read more...
the month will have 5 fridays only if it has 30 days and first friday is 1st or 2nd day of the month or if it has 31 days and the first friday is 1st, 2nd or 3rd day of the month, so you can make conditional statement based on this calculation for 5th friday
for($i=0;$i<=5;$i++)
{
echo date("d/m/y", strtotime('+'.$i.' week friday september 2012'));
}
I used this as the basis for my own solution:
$fridays = array();
$fridays[0] = date('d',strtotime('first fri of this month'));
$fridays[1] = $fridays[0] + 7;
$fridays[2] = $fridays[0] + 14;
$fridays[3] = $fridays[0] + 21;
$fridays['last'] = date('d',strtotime('last fri of this month'));
if($fridays[3] == $fridays['last']){
unset($fridays['last']);
}
else {
$fridays[4] = $fridays['last'];
unset($fridays['last']);
}
print_r($fridays);
I needed to get an array of every Friday in a month, even if there were 5 and this seemed to do the trick using the original question as my basis.
<?php //php 7.0.8
$offDays = array();
$date = date('2020-02');
$day= 'Friday';
$offDays[0] = date('d',strtotime("first {$day} of ".$date));
$offDays[1] = $offDays[0] + 7;
$offDays[2] = $offDays[0] + 14;
$offDays[3] = $offDays[0] + 21;
$offDays['last'] = date('d',strtotime("last {$day} of ".$date));
if($offDays[3] == $offDays['last']){
unset($offDays['last']);
}
else {
$offDays[4] = $offDays['last'];
unset($offDays['last']);
}
foreach($offDays as $off){
echo date('Y-m-d-D',strtotime(date($date."-".$off)));
echo "\n";
}
?>

Categories