As per this question I have found some code that will display all the Sundays in a given month.
<?php
function getSundays($y, $m)
{
return new DatePeriod(
new DateTime("first sunday of $y-$m"),
DateInterval::createFromDateString('next sunday'),
new DateTime("last day of $y-$m")
);
}
foreach (getSundays(date('Y'), date('m')) as $sunday) {
echo $sunday->format("l, Y-m-dn");
}
?>
What I would like to get is the last four Sundays up until todays date.
I’ve used Moment.js in the past as part of another jQuery & Twitter Bootstrap plugin and think that on the front end at least this is what could be used.
Let’s say for example that today is Wednesday 13 May 2015. The last four Sundays will be
- 10 May 2015
- 3 May 2015
- 26 April 2015
- 19 April 2015
Let’s say today is Sunday 19 May, then the last four will be
- 17 May 2015
- 10 May 2015
- 3 May 2015
- 26 April 2015
This is for a simple timesheet application as part of a form. The backend is Laravel 5 (PHP) and the front end so far is simple vanilla JavaScript with some jQuery where necessary. I don’t mind how it is achieved as once I have the dates I can manipulate as necessary.
4
Answers
As I am using Laravel I thought I should be able to use Carbon (I was right). I have posted this answer for myself for future reference and for others.
And with the nice format
You can get back from the previous week then from there, walk with that period you already have then interval next sunday:
Sample Output
A littel shorter solution:
Here is a javascript solution.
I put some extra code in to find the current Year’s end of year date.
can leave that out and input the date directly.
gets you an array with sundays and outputs:
to the console