Second Saturday of Month Function in PHP - php

I found this PHP code credit to creator and want to implement it a different way:
The goal is to have the code automatically adjust the following statement to be the second Saturday of every month from now until eternity:
Next membership meeting: Saturday, MONTH, DAY, YEAR, 11 a.m. to noon.
As in: "Saturday, February 12, 2011, 11 a.m. to noon."
I am no PHP guru, can someone kindly edit it to work?
<?php
function nextMeeting($nextMonth = false) {
$day=date("j");
$month=date("n");
$year=date("Y");
if ($nextMonth) {
$day=1;
if ($month == 12) {
$month=1;
$year++;
} else {
$month++;
}
}
$dayofweek=date("w");
$firstOfMonth=date("w",mktime(0, 0, 0, $month , 1, $year ));
// figure out what date is the second Saturday of the month
if ( $firstOfMonth > 0 ) {
$firstSunday= 8 - $firstOfMonth;
} else {
$firstSunday= 1;
}
$firstSundayDate=date("D",mktime(0, 0, 0, $month ,
$firstSunday, $year));
// figure out what date the third monday of the month is
if ( $firstOfMonth > 1) {
$offSet = 8 - $firstOfMonth;
} elseif ( $firstOfMonth == 0 ) {
$offSet=1;
} else {
$offSet=0;
}
$thirdMonday= 15 + $offSet;
$thirdMondayDate=date("D",mktime(0, 0, 0, $month ,
$thirdMonday, $year));
// lets see which of these dates now applies
if ($day <= $firstSunday) {
// we didn't miss the first meeting
$nextMeeting=$firstSunday;
$nextMeetingDate=mktime(0, 0, 0, $month ,
$nextMeeting, $year);
} elseif ( ($day > $firstSunday) && ($day <= $thirdMonday) ) {
// we missed the first meeting of the month, but can still make the second
$nextMeeting=$thirdMonday;
$nextMeetingDate=mktime(0, 0, 0, $month ,
$nextMeeting, $year);
} else {
// we need to wait until next month
$nextMeetingDate=nextMeeting(1);
$nextMeeting=nextMeeting(1);
}
return $nextMeetingDate;
}
$meeting=nextMeeting();
echo "Next membership meeting is on " . date('l dS \of F Y', $meeting);
?>

How about you save about 5000 lines and try this
<?
echo date('Y-m-d', strtotime('second saturday of february 2011'));
Edit
Ok, I lied in the comments, I will write it for you.
<?
$now=date("U");
$monthyear=date("F Y");
$secondsat=date('U', strtotime($monthyear.' second saturday'));
if ($now>$secondsat) {
$monthyear=date("F Y", "next month");
$secondsat=date('U', strtotime($monthyear.' second saturday'));
}
echo date("m/d/Y",$secondsat);

You could change the function a little like this:
function nextMeeting($date = null)
{
$day = date("j", $date);
$month = date("n", $date);
$year = date("Y", $date);
// remove the nextMonth bit
$dayofweek=date("w", $date);
$firstOfMonth=date("w",mktime(0, 0, 0, $month , 1, $year ));
// all the same between here and the end
return $nextMeetingDate;
}
for ($i = 0; $i < 12; $i++) {
$date = mktime(0, 0, 0, date('m') + $i, date('d'), date('y'));
echo "Next membership meeting is on " . date('l dS \of F Y', nextMeeting($date));
}
That should get you the next 12 meetings after today...

I needed to find the DTS date range, so here's how I did it:
$year = date("Y");
$dtsStart = date('Y-m-d 02:00:00', strtotime("Second Sunday Of March {$year}"));
$dtsEnd = date('Y-m-d 02:00:00', strtotime("First Sunday Of November {$year}"));
And of course you can replace the month with some simple coding as well.

Related

calendar date getting back -1 day, what is wrong, alternate solution?

I'm trying to go back one day in the calendar – What am I doing wrong?
My approach:
$weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
///////
function getDates($year) {
$dates = array();
date("L", mktime(0, 0, 0, 7, 7, $year)) ? $days = 366 : $days = 365;
///
for($i = 1; $i <= $days; $i++) {
// get Unix timestamp for a date
$month = date('F', mktime(0, 0, 0, 1, $i, $year));
$wk = date('W', mktime(0, 0, 0, 1, $i, $year));
$wkDay = date('D', mktime(0, 0, 0, 1, $i, $year));
$day = date('d', mktime(0, 0, 0, 1, $i, $year));
///
$dates[$month][$wk][$wkDay] = $day;
}
return $dates;
}
//////
$year = 2020; // from this Year
$dates = getDates($year);
$countW = 1; // for counting weeks
// Output code
echo '<h2><span>Calendar '.$year.'</span></h2>';
foreach($dates as $month => $weeks) {
echo '<div>';
echo '<table>';
echo '<caption>'.$year.' '.$month.'</caption>';
echo '<tr>';
echo '<th>W</th>';
echo '<th>'.implode('</th><th>', $weekdays).'</th>';
echo '</tr>';
echo '<tr>';
foreach ($weeks as $week => $days){
echo '<tr><td>'.$countW++.'</td>';
foreach ($weekdays as $day) {
echo '<td>';
/* I'm overwhelmed here! */
echo isset($days[$day]) ? $days[$day] : date('d', strtotime('-1 day')); // outputted is 5
echo '</td>';
}
echo '</tr>';
}
echo '</tr>';
echo '</table>';
}
I tried the following codes:
date('d', strtotime('-1 day')) // outputted: 5 (today is 6)
$jd = gregoriantojd(01,06,2020); echo jddayofweek($jd,2); // outputted: Mon (today is Tue)
With this code I get the day from the current day before.
It is expected the day before the specified day
what is happening
is expected
With this code I get the day from the current day before. It is expected the day before the specified day
The day that is "specified" here date('d', strtotime('-1 day')) is the current day.
Generally speaking, a (American) monthly calendar will leave a blank space if the day is not in the month. For example:
That would be a super simple fix to the problem. If not, you'll need to adjust your thinking (and the code!). In the case of the first week of January, the dates for Mon and Tues are -2 and -1 from the first day of January. Similarly, in the last week they are -2 and -1 from the first day of February (or +1, +2 from the last day of January).

PHP - How to calculate one month or one year later

I'd like to calculate next billing date of Recurly plan in PHP.
There are 2 types of billing cycle: yearly | monthly.
I tried to use DateTime and DateInterval classes, but didn't get expected results.
<?php
$referenceTime = new \DateTime('2016-01-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-03-02 00:00:00.000000'
Adding one month to the 31st of Januray gives me the second of March and not the 29th (or 28th) of February as I would expect.
The same for the 31st of August:
<?php
$referenceTime = new \DateTime('2016-08-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-10-01 00:00:00.000000'
If yearly, I expect Feb 29, 2016 + 1 year => Feb 28, 2017
Thanks.
Try this, if date > 28 use last day of next month else use +1 month
$get_date = strtotime("31-01-2016");
$dt = explode("-",$get_date);
$dt = $dt[0];
var_dump(($dt > 28) ? date("d-m-Y", strtotime("31-01-2016 last day of next month")) : date("d-m-Y", strtotime("31-01-2016 +1 month")));
DEMO
You can call modify with PHP's DateTime object to calculate the next date relative to the current date. The following code shows how you would do it with your specific situation.
$next_bill_date = new DateTime();
switch($plan_interval_unit) {
case "year":
$next_bill_date->modify("last day of next month");
break;
case "month":
$next_bill_date->modify("last day of this month next year");
break;
}
May be something like that:
if (date('d') !== date('d', strtotime('+1 month'))
date ('Y-m-d H:i:s', strtotime('last day of next month'));
if (date('d') !== date('d', strtotime('+1 year'))
date ('Y-m-d H:i:s', strtotime('last day of this month next year'));
You can use PHP inbuilt strtotime() function
// One month from today
$date = date('Y-m-d', strtotime('+1 month'));
// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2016-12-06')));
function get_next_billing_date($now, $type, $format = 'Y-m-d')
{
$date = new DateTime($now);
$y = $date->format("Y");
$m = $date->format("m");
$d = $date->format("d");
if ($type == 'year') {
$y++;
if ($m == 2 && $d == 29) {
$d = 28;
}
} else if ($type == 'month') {
if ($m == 12) {
$y++;
$m = 1;
} else {
$m++;
}
$first_date = sprintf("%04d-%02d-01", $y, $m);
$last_day_of_next_month = date('t', strtotime($first_date));
if ($d > $last_day_of_next_month) {
$d = $last_day_of_next_month;
}
} else {
// not supported
return false;
}
$date->setDate($y, $m, $d);
return $date->format($format);
}

Why does the following code return the second friday in November but first friday in December?

sorry if this is a duplicate. Why does the following code error so? It returns Dec 6th currently, the first Friday in December (asking on 8 Oct 2013)
$thisMonth = date('m');
$year = date("Y");
$thismonthName = date("M.", mktime(0, 0, 0, $thisMonth,0,$year));
if ($thisMonth < 12) {
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,1,$year));
} else {
$nextMonth = 1;
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,1,$nextYear));
}
$thisDate = date('M j', strtotime($nextmonthName . $year . "first friday"));
print ("second friday next month is " . $thisDate);
but modifying it to be only next month, like so,
$thisMonth = date('m');
$year = date("Y");
$thismonthName = date("M.", mktime(0, 0, 0, $thisMonth,0,$year));
if ($thisMonth < 12) {
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,0,$year));
} else {
$nextMonth = 1;
$nextmonthName = date("M.", mktime(0, 0, 0, $nextMonth,0,$nextYear));
}
$thisDate = date('M j', strtotime($nextmonthName . $year . "first friday"));
print ("second friday next month is " . $thisDate);
returns Nov 8th, the second Friday in November. Why is that?
You REALLY should investigate DateTime, DateInterval, DatePeriod classes. They make this sort of thing trivial.
$date = new DateTime();
$interval = DateInterval::createFromDateString('second friday of next month');
$date->add($interval);
echo 'Second Friday next month is ' . $date->format('Y-m-d');
Or to get 2nd Friday for next 3 months:
$date = new DateTime();
$recurrence_count = 3;
$interval = DateInterval::createFromDateString('second friday of next month');
$period = new DatePeriod($date, $interval, $recurrence_count);
foreach ($period as $dt) {
echo $dt->format('Y-m-d');
}
Your code is way too complicated.
$secondNextFriday = new DateTime('first friday of +2 months'); // First friday in december

Using PHP date to display weekly dates

I'm not really sure what to call this. But basically I want to be able to have a user click on "Popular Stories from This Week", and it will take them to a page that will have other stuff but mainly the dates. For example, July 10-17.
I'm currently using this code:
$seven_days_ago = date('j') - 7;
$time_span = date('F ' . $seven_days_ago . ' - j');
Now, I ran into a problem when we entered July, because it would display something like July -3 - 4. I need a way for it to detect if the seven days ago variable is negative, and figure out what it should display. Help?
Thanks!
You can use strtotime for this:
$seven_days_ago = strtotime('-7 days');
$time_span = date('F j', $seven_days_ago) . ' - ' . date('F j');
The above gives me "June 28 - July 5" for $time_span.
you need to use strtotime
$timeago = strtotime("7 days ago");
What about using
$unix_timestamp = mktime(0, 0, 0, date("m"), date("d")-7, date("Y"));
and just take the returned unix timestamp?
Update
Just a little code snipped that will give you a full working example. However I don't like it that much :)
<?php
$today = date("d F");
list($today_day, $today_month) = explode(" ", $today);
$previous = date("d F", mktime(0, 0, 0, date("m"), date("d")-7, date("Y")));
list($previous_day, $previous_month) = explode(" ", $previous);
if($today_month != $previous_month){
echo $previous_month." ".$previous_day." - ".$today_month." ".$today_day;
}else{
echo $today_month." ".$previous_day." - ".$today_day;
}
die();
?>
i just created a very nifty little function. Just pass it the Week number, it returns you an array of that week's days dates.
function findWeekDates($weekNumber=null, $year=null ) {
// receives a specific Week Number (0 to 52) and returns that week's day dates in an array.
// If no week specified returns this week's dates.
$weekNumber = ($weekNumber=='') ? date('W'): $weekNumber ;
$year = ($year=='') ? date('Y'): $year ;
$weekNumber=sprintf("%02d", $weekNumber);
for ($i=1;$i<=7;$i++) {
$arrdays[] = strtotime($year.'W'.$weekNumber.$i);
}
return $arrdays;
}
Example Usage - find a given week start and end dates:
$week= (isset($_GET['week']) && $_GET['week'] !=='')? $_GET['week'] : date('W') ;
$year = (isset($_GET['year']) && $_GET['year'] !=='')? $_GET['year'] : date('Y') ;
if($week>52) {
$week = 1;
$year++;
}else if($week<1) {
$week=52;
$year--;
}
$week_days = findWeekDates($week, $year);
$starting_date = date('Y-m-d', $week_days[0]);
$ending_date = date('Y-m-d', $week_days[6]);
hope this helps...

In PHP, is there an easy way to get the first and last date of a month?

I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?
$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));
See date() in PHP documentation.
First day is always YYYY-MM-01, isn't it? Example: date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))
Last day is the previous day of the next month's first day:
$date = new DateTime("2008-09-01");
$date->modify("-1 day");
echo $date->format("Y-m-d");
The first day of the month is always 1.
So it will become
YYYY-MM-01
the last day can be calculated as:
<?php
$num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There was $num days in August 2003";
?>
OK, first is dead easy.
date ('Y-m-d', mktime(0,0,0,MM,01,YYYY));
Last is a little trickier, but not much.
date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY));
If I remember my PHP date stuff correctly...
**edit - Gah! Beaten to it about a million times...
Edit by Pat:
Last day should have been
date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
<?php
echo "Month Start - " . $monthStart = date("Y-m-1") . "<br/>";
$num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y"));
echo "Monthe End - " . $monthEnd = date("Y-m-".$num);
?>
The easiest way to do this with PHP is
$dateBegin = strtotime("first day of last month");
$dateEnd = strtotime("last day of last month");
echo date("MYDATEFORMAT", $dateBegin);
echo "<br>";
echo date("MYDATEFORMAT", $dateEnd);
Or the last week
if (date('N', time()) == 7) {
$dateBegin = strtotime("-2 weeks Monday");
$dateEnd = strtotime("last Sunday");
} else {
$dateBegin = strtotime("Monday last week");
$dateEnd = strtotime("Sunday last week");
}
Or the last year
$dateBegin = strtotime("1/1 last year");
$dateEnd = strtotime("12/31 this year");
By the way #ZombieSheep solution
date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY));
does not work it should be
date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
Of course #Michał Słaby's accepted solution is the simplest.
Just to verify that I didn't miss any loose ends:
$startDay = 1;
if (date("m") == 1) {
$startMonth = 12;
$startYear = date("Y") - 1;
$endMonth = 12;
$endYear = date("Y") - 1;
}
else {
$startMonth = date("m") - 1;
$startYear = date("Y");
$endMonth = date("m") - 1;
$endYear = date("Y");
}
$endDay = date("d") - 1;
$startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear));
$endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear));
try this to get the number of days in the month:
$numdays = date('t', mktime(0, 0, 0, $m, 1, $Y));
Example; I want to get first day and last day of current month.
$month = (int) date('F');
$year = (int) date('Y');
date('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first
date('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last
When you run this for instance at date 2015-01-09, the first and last values will be sequentially;
2015-01-01
2015-01-31
Tested.
From here(get next month last day) that is marked as duplicated, so i can't add comment there, but people can got bad answers from there.
Correct one for last day of next month:
echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t'));
Correct one for first day of next month:
echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01'));
Code like this will be providing March from January, so that's not what could be expected.
echo ((new DateTime())->modify('+1 month')->format('Y-m-t'));
proper way to build a relative date from now is:
//bad example - will be broken when generated at 30 of December (broken February)
echo date("Y-m-d", strtotime("now"))."\n";
echo date("Y-m-d", strtotime("now + 1 month"))."\n";
echo date("Y-m-d", strtotime("now + 2 month"))."\n";
echo date("Y-m-d", strtotime("now + 3 month"))."\n";
//good example, you can change first day to last day or any day
echo date("Y-m-d", strtotime("first day of this month"))."\n";
echo date("Y-m-d", strtotime("first day of next month"))."\n";
echo date("Y-m-d", strtotime("first day of +2 month"))."\n";
echo date("Y-m-d", strtotime("first day of +3 month"))."\n";
and the result will be:
2021-12-30
2022-01-30
2022-03-02
2022-03-30
2021-12-01
2022-01-01
2022-02-01
2022-03-01

Categories