I'm trying to create a simple weekly agenda. Here is my code:
$daterange = new DatePeriod(
new DateTime('2016-04-08'),
new DateInterval('P1D'),
new DateTime(date('Y-m-d',strtotime ( '1 week' , strtotime ( '2016-04-08' ) )))
);
Then a simple loop:
foreach ($daterange as $k => $row) {
echo $row->format('d') ." - " . $row->format('D') . "<br>";
}
Produces something like:
08 - Fri
09 - Sat
10 - Sun
11 - Mon
12 - Tue
13 - Wed
14 - Thu
Which works perfectly fine, but what I need is to display dates starting from Sunday or Monday, based on first day of the week. The desired result should be:
10 - Sun
11 - Mon
12 - Tue
13 - Wed
14 - Thu
15 - Fri
16 - Sat
You could use something like this:
date('Y-m-d', strtotime('last Monday', '2016-04-08'));
You can replace last Monday with next Monday/last Sunday/next Sunday, depending on what you need. This will give you the previous/next first day of the week for current day. You could then obtain a 7 day interval, starting from this date.
It is generally considered bad to mix DateTime and strtotime(), date(), etc., so here's another solution:
// The question is ambiguous on this, so we'll use a
// variable to configure the preferred first weekday
$firstWeekDay = 'Sunday';
$dateTime = new DateTime();
// If today isn't the first week day, get the last one
if ($dateTime->format('l') !== $firstWeekDay)
{
$dateTime->modify("last {$firstWeekDay}");
}
$period = new DatePeriod(
$dateTime,
new DateInterval('P1D'),
6 // Just tell PHP to create 6 (7 - the 1 start day) more dates
);
Related
I need to get a list of dates that should range from the current day, up to the specified day (saturday, in this case) of the following week.
Example:
Today is friday, august 1st 2014, so it should get the dates starting from today up to saturday, august 9th 2014:
fri, 2014-08-01
sat, 2014-08-02
(sun excluded)
mon, 2014-08-04
tue, 2014-08-05
wed, 2014-08-06
thu, 2014-08-07
fri, 2014-08-08
sat, 2014-08-09
(sun excluded)
How can I go about this?
I was thinking on using the DateInterval class, this is what I've got so far:
$now = date('Y-m-d');
$start = new DateTime($now);
$end = new DateTime($now);
$oneweek = new DateInterval('P1W');
$oneday = new DateInterval('P1D');
$days = array();
foreach(new DatePeriod($start, $oneday, $end->add($oneweek)) as $day) {
$day_num = $day->format('N');
if($day_num < 7) {
$days[$day->format('Y-m-d')] = 'valid date';
}
}
It works fine for excluding the sundays, but it only goes up to 1 week after the current date, i.e. 7 days. So I was wondering if there was a way of making $end to be something like: 'the saturday of the following week'.
There's actually a way to do that, if you take a look at the comments section of the DatePeriod's Manual page, you'll find an usage example of the DateInterval class' createFromDateString static method, by jkaatz at gmx dot de (2009-07-10 01:55):
$interval = DateInterval::createFromDateString('last thursday of next month');
Using the same approach, you can construct a date interval by using the following string:
sunday of next week
And it would let you get all the dates between the current day (including the current week's saturday) up to the next week's saturday (since DatePeriod counts up to, but not including, the end date).
You can find more information of the createFromDateString's method on its manual pages, you can also find more on the syntax, keywords and notations for constructing interval strings on the Relative Formats Manual pages, which are also used by the strtotime() function and the DateTime class.
I am trying creating a script that will change an image on a page if the last friday in the month is during the current week. For example if I am on any of the day of week (Monday to Sunday) that contains the last friday of the month during the week I will get an output that differs from the rest of the month.
I was helped on a previous question with this code but it only works if the last day of the month is today. However I need the function to know if the last day of the month is on either Monday, Tuesday, Wednesday, Thursday is still in the current week as my week runs from Monday to Sunday:
// Be sure to check your timezone `date_default_timezone_set`
$today = new DateTime();
$last_friday = new DateTime('last Friday of this month');
// For testing
$friday_april = new DateTime('2014-4-25');
if ($today->format('Y-m-d') === $last_friday->format('Y-m-d')) {
print 'Today is friday';
}
if ($friday_april->format('Y-m-d') === $last_friday->format('Y-m-d')) {
print 'Yes, a test friday is also a friday';
}
Any help would be great!
Change your date format for the comparisons.
W should suffice.
Why?!
Because then the same string (the ISO week number) will be produced for dates within the same week (beginning on Mondays).
Given this month, April 2014, the week number of the week containing the last Friday is 17.
2014-04-19 Sat => 16 ✗
2014-04-20 Sun => 16 ✗
2014-04-21 Mon => 17 ✓
2014-04-22 Tue => 17 ✓
2014-04-23 Wed => 17 ✓
2014-04-24 Thu => 17 ✓
2014-04-25 Fri => 17 ✓
2014-04-26 Sat => 17 ✓
2014-04-27 Sun => 17 ✓
2014-04-28 Mon => 18 ✗
2014-04-29 Tue => 18 ✗
2014-04-30 Wed => 18 ✗
Summary
if ($today->format('W') === $last_friday->format('W')) {
// Do victory dance
}
You need a loop. Go through the loop and add a day until you get to the next month. Count how many Fridays you encounter (including today) from today to the start of the next month. If its only 1, then the last Friday is in this week.
use strtotime and date so it should look like this:
$today = new DateTime();
$last_friday = strtotime('last Friday of this month');
// For testing
$friday_april = new DateTime('2014-4-25');
if ($today->format('Y-m-d') === date('Y-m-d', $last_friday)) {
print 'Today is friday';
}
if ($friday_april->format('Y-m-d') === date('Y-m-d', $last_friday)) {
print 'Yes, a test friday is also a friday';
}
$today = getdate();
$weekStartDate = $today['mday'] - $today['wday'];
$weekEndDate = $today['mday'] - $today['wday']+6;
echo "week start date:".$weekStartDate;
echo "<br/>";
echo "week end date:".$weekEndDate;
By this code you can get start and end days of the current week
$thisWeekHasLastFridayOfMonth = function () {
$lastFridayThisMonth = date('Y-m-d',strtotime('last Friday of this month'));
$testDate = date('Y-m-d',strtotime('today'));
$thisWeekSunday = (date('N',strtotime($testDate))!=1?date('Y-m-d',strtotime('last Sunday')):date('Y-m-d'));
$thisWeekSaturday = (date('N',strtotime($testDate))!=7?date('Y-m-d',strtotime('next Saturday')):date('Y-m-d'));
//echo $lastFridayThisMonth . '<br>' . $thisWeekSunday . '<br>' . $thisWeekSaturday;
if (strtotime($lastFridayThisMonth) >= strtotime($thisWeekSunday) &&
strtotime($lastFridayThisMonth) <= strtotime($thisWeekSaturday))
return true;
else
return false;
};
echo $thisWeekHasLastFridayOfMonth?'True':'False';
This question already has answers here:
Get Start and End Days for a Given Week in PHP
(16 answers)
Closed 9 years ago.
I am selecing a date from jquery datepicker and I want to pick the starting and ending date of the week that precedes this date. - for example picking April 10, 2013 should return March 31, 2013 and April 6, 2013.
Sunday is the first day of the week and Saturday is last.
Below is my code.
$weekday = $d->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 0); //to make week start from monday till sunday add 1 to weekday -
$start1 = $d->modify("-$diff day");
$start_date = $d->format('Y-m-d');
$end1 = $d->modify('+6 day');
$stop_date = $d->format('Y-m-d');
The code works fine, at least mostly. However, when I pick any sunday I get a wrong a non expected result which is the previous week of the previous week.
for example, if I select March 31, 2013 - I should get march 24 and march 30,, but I am getting march 28 and march 24.
Where am I going wrong ?
Try this, it should solve your problem:
$input = 'April 10, 2013'; // come from jquery
$dt = new DateTime($input . ' -1week');
$monday = clone $dt->modify(('Sunday' == $dt->format('l')) ? 'Monday last week' : 'Monday this week');
$sunday = clone $dt->modify('Sunday this week');
printf("You've selected a date in the week from %s to %s\n",
$monday->format('Y-m-d'),
$sunday->format('Y-m-d')
);
How can I calculate Next Business Day given a Zend_Date and a cutoff time of 5pm? Business days are M-F (weekdays).
Example:
Fri 4 pm should return same date
Sat anytime should return next Mon
Tue 8 pm should return Wed
I think this has been asked before, Next business day of given date in PHP, but here it is using Zend_Date:
$now = new Zend_Date();
if (($now->get(Zend_Date::WEEKDAY_DIGIT) % 6 == 0)
|| ($now->isLater('17:00:00', Zend_Date::TIMES))
) {
$now->set(
strtotime('+1 weekday', $now->toString(Zend_Date::TIMESTAMP)),
Zend_Date::TIMESTAMP
);
}
echo $now->toString(Zend_Date::W3C);
How would I put together a PHP5 function that would find the current calendar week and return the dates of each day in the week as an array, starting on Monday? For example, if the function were run today (Thu Feb 25 2010), the function would return an array like:
[0] => Mon Feb 22 2010<br />
[1] => Tue Feb 23 2010<br />
[2] => Wed Feb 24 2010<br />
[3] => Thu Feb 25 2010<br />
[4] => Fri Feb 26 2010<br />
[5] => Sat Feb 27 2010<br />
[6] => Sun Feb 28 2010<br />
It doesn't matter what format the dates are stored as in the array, as I assume that'd be very easy to change. Also, it'd be nice to optionally be able to supply a date as a parameter and get the calendar week of that date instead of the current one.
Thanks!
I suppose a solution would be to start by getting the timestamp that correspond to last monday, using strtotime :
$timestampFirstDay = strtotime('last monday');
But if you try with today (thursday), with something like this :
$timestampFirstDay = strtotime('last thursday');
var_dump(date('Y-m-d', $timestampFirstDay));
you'll get :
string '2010-02-18' (length=10)
i.e. last week... For strtotime, "last" means "the one before today".
Which mean you'll have to test if today is "last monday" as returned by strtotime plus one week -- and, if so, add one week...
Here's a possible (there are probably smarter ideas) solution :
$timestampFirstDay = strtotime('last monday');
if (date('Y-m-d', $timestampFirstDay) == date('Y-m-d', time() - 7*24*3600)) {
// we are that day... => add one week
$timestampFirstDay += 7 * 24 * 3600;
}
And now that we have the timestamp of "last monday", we can write a simple for loop that loops 7 times, adding 1 day each time, like this :
$currentDay = $timestampFirstDay;
for ($i = 0 ; $i < 7 ; $i++) {
echo date('Y-m-d', $currentDay) . '<br />';
$currentDay += 24 * 3600;
}
Which will give us this kind of output :
2010-02-22
2010-02-23
2010-02-24
2010-02-25
2010-02-26
2010-02-27
2010-02-28
Now, up to you to :
Modify that for loop so it stores the dates in an array
Decide which format you want to use for the date function
Have fun ;-)
Lessee. . First, to avoid any timezone issues I'd peg to noon on the day you want to compare against, so an hour either way won't cause any problems.
$dateCompare = time(); // replace with a parameter
$dateCompare = mktime(12, 0, 0, date('n', $dateCompare),
date('j', $dateCompare), date('Y', $dateCompare));
Then find the day of week of your date.
$dow = date('N', $dateCompare);
1 is Monday, so figure out how many days from Monday we are.
$days = $dow - 1;
Now subtract days worth of seconds until you get back to Monday.
$dateCompare -= (3600 * 24 * $days);
Now assemble your array of days.
$output = array();
for ($x = 0; $x < 7; $x++) {
$output[$x] = $dateCompare + ($x * 24 * 3600);
}
This is an array of timestamps, but you could store the dates as strings if you prefer.