PHP strtotime - get next closest "second sunday of the month" - php

I am trying to get the timestamp of the next "second sunday of the month", regardless it is in the current month or in the next month.
The requirements are to use the strtotime function, only once, and without second parameter, nothing more (these constraints come from legacy code).
Basically the PHP code to get that must be only:
strtotime('_a_string_here_');
And the string must be a generic string. It can't contain something like 'feb 2011'.
Basically I can just drop a static string as first argument of the strtotime function.
I have tried all of these but they don't give me what I want (now the date is Thu 2011-02-24):
strtotime('second sunday') // it returns '2011-03-06 00:00:00'
strtotime('second sunday of the month ') // 1970-01-01 00:00:00
strtotime('+0 month second sun') // it returns '2011-03-06 00:00:00'
Thanks,
Dan

Try this one:
strtotime('+2 week Sunday')
New Answer:
I think you're expecting strtotime to be too smart. By not providing a month in the string, or a second parameter, it can only assume 'current time'.
There is no word support for conditionals like 'second sunday of current month if not past, else second sunday of next month'.
IMO adding stuff like that to strtotime would make it too complex to be of any use in normal operations. The correct solution would most likely be to make two calls to strtotime (the first to see if the current month has past, the second only if we need the next month).
I don't know why your constraints exist, but you should probably start figuring out how you can change the constraints.

None of the suggestions worked for me.
Here's what did though:
date('m/d/Y', strtotime('Second Sunday Of March 2015'));

For the discussion about the "next month problem" check http://derickrethans.nl/obtaining-the-next-month-in-php.html

// second sun next month
strtotime('+0 month +2 week sun');

To solve this you just need to normalize to the first of the month in question. So say you want the second Sunday of March for daylight savings.
date('m/d/Y',strtotime('03/01/2011 second sunday'));
or more generically
date('m/d/Y',strtotime('03/01'.date('Y').' second sunday'));
Hope this helps.

Have you tried.
strtotime('second sunday of this month');

Related

PHP doesn't give a proper output for month substraction

Code:
$time = strtotime('2020-03-31');
echo date('Y-m-d', strtotime('-1 month', $time));
Expected Result: Any date from Feb 2020
Actual Result: 2020-03-02
Is there any better way to add or subtract a month from a given date?
Months are an awkward interval to work with, because they don't have a fixed length. Should the algorithm assume that by "1 month" you mean "30 days", or "31 days", or should it just try subtracting 1 from the "month" field in the date structure?
The last option is what is happening here: given "2020-03-31", PHP's date library is subtracting 1 from the "03" to give "2020-02-31". Since that's an invalid date (February 2020 had 29 days), it then "normalises" it to a real date - 2 days after the 29th February was the 2nd March.
Probably you want to use a more specific period to subtract, like 30 days - although note that if the initial input is "2020-03-01" that will give you "2020-01-31", not "2020-02-01".
Ultimately, this is a problem with our irregular calendar, rather than with PHP. It's really up to you to define what you mean by "a month before", and use a more specific algorithm that captures that requirement.
You can make code like below
<?php
$time = strtotime('2020-03-1 -32 days');
echo date('M-Y', $time); // output Feb-2020
?>
The above code will return date as you expected

this week in PHP 5.3

I try to find an answer but without result
the problem is:
in sunday function return date for Monday next week
$date = new DateTime();
$date->setTimezone(new DateTimeZone('Europe/Moscow'));
$date->setTimestamp(strtotime('Monday this week'));
echo $date->format("d.m.Y");
but in other days (except Sunday) its return correct value of Monday.
I ever set locale manualy , which has a monday - the first day of week, but PHP "think" the Sunday is still firs day. is it bug ?? or i do some wrong ?
There seem to be known idiosyncrasies with strtotime. It's mentioned in the comments:
http://www.php.net/manual/en/datetime.formats.relative.php#108317
They don't mention different locales specifically but it would be extremely unsurprising if strtotime() does not correctly behave for next/this week under different locales.
Try this Monday or next Monday and see if one of those gets what you want.

Why is strtotime one week off?

strtotime("third Saturday October 2011")
Should be 10/15/2011. However, it's coming up at 10/22/2011. I assume this is because October 2011 starts on a Saturday and PHP is looking at the first full week. Since 10/1/2011 is a Saturday not a full week it ignores it.
Some research suggested putting "of" between the day of the week and the month should fix it but that doesn't work.
Any suggestions on why this is happening and what I can do to correct it?
This is a documented flaw in PHP <5.2.7 (see strtotime):
In PHP 5 prior to 5.2.7, requesting a given occurrence of a given
weekday in a month where that weekday was the first day of the month
would incorrectly add one week to the returned timestamp. This has
been corrected in 5.2.7 and later versions.
You'll need to upgrade PHP, or use a work around like Jonathan Kuhn suggests.
I was getting the same results as you on php 5.2.6. This works for me although not ideal.
echo date('Y-m-d', strtotime('Saturday October 2011 +2 weeks'));
<?php echo date('Y-m-d', strtotime('third Saturday of October 2011')); ?>
Works fine for me. Output is 2011-10-15.

Month by week of the year?

I'm trying to get the number of the month of the year by the number of a week of the year and the year.
So for example week 1 is in january and returns 1, week 6 is in february so I want 2.
I tried to go with date_parse_from_format('W/Y') but had no success (it's giving me errors).
Is there any way to go with date_parse_from_format() or is there another way?
print date("m",strtotime("2011-W6-1"));
(noting that in 2011, January has six weeks so week 6 (by some definitions) is in month 1).
Just wanted to add a note for the first answer, the week number should be 01-09 for Weeks 1 through 9 (it will always give month 1 if you don't add the leading zero)
date("m",strtotime("2011-W06-1"));
Using PHP DateTime objects (which is the preferred way of dealing with dates see links below for more info) you can accomplish it this way:
$dateTime = new \DateTime();
$dateTime->setISODate($year,$week);
$month = $dateTime->format('n');
Note that the following will not work as week "W" is not a supported format:
$month = \DateTime::createFromFormat("W/Y ", "1/2015")->format('n');
The format used by this method is the same supported by the function you where trying to use date_parse_from_format, hence the errors.
Why PHP DateTime Rocks
DateTime class vs. native PHP date-functions
strtotime notes
PHP/Architect's Guide to Date and Time Programming (Chapter 2)
Something like this will do, this is also tested and works:
function getMonthByNumber($number,$year)
{
return date("F",strtotime('+ '.$number.' weeks', mktime(0,0,0,1,1,$year,-1)));
}
echo getMonthByNumber(27,2011);
Hope this helps

work out the date of the fourth saturday in the current month

Bit stuck about how to go about this one. Given the current month, I need to to return the date of the fourth saturday of each month.
e.g. This month would be Feb 20th, next would be March 27th.
Thanks
I'm not a PHP coder, however, it seems strtotime is what you're after.
You can use strtotime("fourth Saturday") and it will return the 4th saturday.
Check out the strtotime docs.
EDIT:
Just to make the answer complete, thanks to Tom and Paul Dixon
date('dS F',strtotime('Fourth Saturday '.date('F o')));
You can use strtotime to find "next saturday" based on a starting date. If that starting date is the day before the earliest possible preceding day (21st) we get the answer...
//required year/month
$yyyymm="2009-01";
//find next saturday after earliest possible date
$t=strtotime("next saturday", strtotime("{$yyyymm}-21"));
//here you go!
echo "4th saturday of $yyyymm is ".strftime("%Y-%m-%d",$t)."\n";
Earliest possible 4th repeat of a day in any month is the 22nd (1,8,15,22), last possible 4th repeat is 28th (7,14,21,28).
EDIT: Although it's not clear in the documentation, you can request the "fourth saturday" too - use the zeroth day of the month as the basis:
$t=strtotime("fourth saturday", strtotime("{$yyyymm}-00"));
or omit the basis time and specify the month and year directly:
$t=strtotime("fourth saturday feb 2009");
Tip of the hat to Robin "I'm not a PHP coder" Day for spotting that :)
The earliest date for the fourth Saturday is the 22nd of the month. So look at the 22nd, see what day of the week it is, if it's not Saturday, add one day to the date, and check again, until you find a match (maximum you would have to check is 6 days).
Find the first Saturday of the month, and then add three weeks to that.
If you don't know when the first Saturday is (or, rather, don't know specifically a date corresponding with a day name), you might want to look at the Doomsday algorithm, which I conveniently looked at for another post with a somewhat similar issue.
function fourth_saturday($year, $month)
{
$info = localtime(mktime(0, 0, 0, $month , 1, $year));
return 28 - $info[6];
}
in PHP rather than pseudo code (think requires 5.2)
$date = getdate();
$date-> setDate($date->format('Y'), $date->format('Y'), '1'); // 1st of month.
while ($date->format('w' != 6)
$date->modify("+1 day");
$date->modify("+21 day"); // date is now on the fourth saturday

Categories