I've been using the syntax Carbon::now()->startOfWeek() and Carbon::now()->endOfWeek() for awhile now.
It returns the first day of the week which is the date of Monday and the last day of the week which is the date of Sunday. (I don't know why it wasn't Sunday and Saturday)
But now, I want to get every day of the current week. So what's left is the dates of Tuesday, Wednesday, Thursday, Friday, and Saturday.
Here's my exact syntax on getting Monday and Sunday.
$monday = Carbon::now()->startOfWeek();
$sunday = Carbon::now()->endOfWeek();
You can progress through the week with addDay().
$monday = Carbon::now()->startOfWeek();
$tuesday = $monday->copy()->addDay();
$wednesday = $tuesday->copy()->addDay();
You can also check which day of the week you have.
$wednesday === Carbon::WEDNESDAY; // true
If you want to get the current week of a spesific day try with this
1.- create a carbon day with the day that you need
$carbaoDay = Carbon::createFromFormat('Y-m-d', $request->day);
//spesific day format 2000-01-00
2 aftert into a for loop just push a day
$carbaoDay->startOfWeek()->addDay($i)->format('Y-m-d');
$carbaoDay->startOfWeek() /// always monday
->addDay($i)->format('Y-m-d'); //$i =1 push: 2000-01-01 ,;//$i =2 push: 2000-01-02
$carbaoDay = Carbon::createFromFormat('Y-m-d', $request->day); //spesific day
$week = [];
for ($i=0; $i <7 ; $i++) {
$week[] = $carbaoDay->startOfWeek()->addDay($i)->format('Y-m-d');//push the current day and plus the mount of $i
}
output:
array:7 [
0 => "2020-01-06"
1 => "2020-01-07"
2 => "2020-01-08"
3 => "2020-01-09"
4 => "2020-01-10"
5 => "2020-01-11"
6 => "2020-01-12"
]
Related
I'm using Bootstrap datepicker and I'd like to get special days of every week ( Like: Monday, Wednesday, Saturday). For example, If we select every monday and Wednesday then select only Monday and Wednesday.
And I want this weekday through month wise, (Like, If we select date 24-jun to 24-july and select only Monday. Then every Monday from 24-jun to 24-july will be selected).
So what would be the correct way to get weekdays using bootstrap datepicker?
Any kind of help would be highly appreciated.
Thanks in advance.
I´ve found the solution :
$start_date = "28-06-2016";
$end_date = "28-07-2016";
$weekdays = [1,2]; // 0 = sunday, 1 = monday ...
$range_date = array();
for ($i = strtotime($start_date); $i <= strtotime($end_date); $i = strtotime('+1 day', $i))
{
if(in_array(date('N', $i), $weekdays))//Monday == 1
{
echo date('l Y-m-d', $i).'<br>'; //prints the date only if it's a Monday or tuseday etc..
}
}
And output :
Tuesday 2016-06-28
Monday 2016-07-04
Tuesday 2016-07-05
Monday 2016-07-11
Tuesday 2016-07-12
Monday 2016-07-18
Tuesday 2016-07-19
Monday 2016-07-25
Tuesday 2016-07-26
I'm looking to find the date of the 29th of this month, the 29th of next month, the 29th of last month and so on...
I know you can use this kind of code to find days of the week:
$friday_last = date("d/m/Y", strtotime("last Friday"));
$friday_due = date("d/m/Y", strtotime("this Friday"));
Is there a similar way to find a certain day (29th) of each month or would I have to use a different code?
You need to use DateTime() as it makes working with dates much easier. You'll notice I start by going to the first day of each month. That's so this doesn't break when you get to the 29th-30th of each month as weird date things start to happen.
echo (new DateTime())->modify('first day of this month')->format("29/m/Y");
echo (new DateTime())->modify('first day of previous month')->format("29/m/Y");
echo (new DateTime())->modify('first day of next month')->format("29/m/Y");
Demo
echo (new DateTime())->modify('first day of this month')->modify('-2 months')->format("29/m/Y");
Demo
Using date() with strtotime() will gives you 29th from each month within this year:
<?php
for ($i = 1; $i <= 12; $i++) {
$d = "2016-" . $i . "-29";
echo "29th of Month $i is: " . date("l", strtotime($d)) . '<br>';
}
?>
Output:
29th of Month 1 is: Friday
29th of Month 2 is: Monday
29th of Month 3 is: Tuesday
29th of Month 4 is: Friday
29th of Month 5 is: Sunday
29th of Month 6 is: Wednesday
29th of Month 7 is: Friday
29th of Month 8 is: Monday
29th of Month 9 is: Thursday
29th of Month 10 is: Saturday
29th of Month 11 is: Tuesday
29th of Month 12 is: Thursday
To create an array with current and next 11 months 29th day (for previous months replace +1 month with -1 month. In this example I use +1 to explain february issue, that is not present in past february):
$baseDate = date_create()->modify( 'first day of this month' );
$dates = array();
for( $i = 0; $i<12; $i++ )
{
$newDate = clone $baseDate;
$dates[] = $newDate->modify( '+28 days' );
$baseDate->modify( '+1 month' );
}
The problem — as you can imagine — is with february:
foreach( $dates as $date )
{
echo $date->format( 'Y-m-d' ).PHP_EOL;
}
Will output:
2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-03-01 <-----
2017-03-29
2017-04-29
If you want a result like “29th month's day OR last month's day” modify above for loop in this way:
for( $i = 0; $i<12; $i++ )
{
$newDate = clone $baseDate;
if( $newDate->modify( '+28 days' )->format( 'm' ) != $baseDate->format( 'm' ) )
{
$newDate->modify( 'last day of previous month' );
}
$dates[] = $newDate;
$baseDate->modify( '+1 month' );
}
Result:
2016-05-29
2016-06-29
2016-07-29
2016-08-29
2016-09-29
2016-10-29
2016-11-29
2016-12-29
2017-01-29
2017-02-28 <-----
2017-03-29
2017-04-29
I'm not sure when this started, but now you can do so by using just date() and strtotime(), like this:
$d = date("Y-m-d 00:00:00", strtotime('first day of 2 months ago'));
$l = date("Y-m-d 00:00:00", strtotime('last day of 2 months ago'));
print_r($d);
print_r($l);
Assuming today (2023-02-01) The above will display:
2022-12-01 00:00:00
2022-12-31 00:00:00
Sample:
https://onlinephp.io/c/db73f
Php is returning an unexpected set of week dates given a specific day. For example, given the date 2015-05-20, the days of the week that should be returned are:
array:7 [
0 => "2015-05-17"
1 => "2015-05-18"
2 => "2015-05-19"
3 => "2015-05-20"
4 => "2015-05-21"
5 => "2015-05-22"
6 => "2015-05-23"
]
Or in plain text May 17th to 23rd, 2015. From what I can tell this is correct. Now, given the date 2015-05-17, I get the following results:
array:7 [
0 => "2015-05-10"
1 => "2015-05-11"
2 => "2015-05-12"
3 => "2015-05-13"
4 => "2015-05-14"
5 => "2015-05-15"
6 => "2015-05-16"
]
Which you will notice is the week before the 17th, or May 11th to 16th, 2015.
Here is the function that is pulling my weekdays:
$days_of_week = array();
for($i = 0; $i <= 6; $i ++){
$days_of_week[] = date("Y-m-d", strtotime(date("o", strtotime($date))."W".date("W", strtotime($date)).$i));
}
Basically, for the 7 days in a given week number (which is 20 in this case), push the formatted value to an array (as shown in the two examples above.) Pre-formatted, the values being pushed are:
2015W200
2015W201
2015W202
2015W203
2015W204
2015W205
2015W206
// Year: 2015, Week: 20, Day(In week): 0-6
I think the issue I'm facing is that ISO-8601 week numbers start from Monday and end at Sunday, but I'm trying to pull a week that starts with Sunday and ends with Saturday (for display on a calendar.) Is there another way to accomplish this?
In fact it's a expected result.
2015-05-17 is in 20th week.
Thus days and week day number are respectively: (10 11, 12, 13, 14, 15, 16) and (0, 1, 2, 3, 4, 5, 6)
See Localized Notations section on docs, in format compounds:
Notation
ISO year with ISO week and day:
YY "-"? "W" W "-"? [0-7]
Where the last token stays for a week day number, starting with sunday to saturday.
So when you loop over week numbers you're getting:
2015W20[0] -> That is, a date on sunday (2015-05-10)
2015W20[1] -> That is, a date on monday (2015-05-18)
So you must especify the correct week number of year:
$days_of_week = array();
$week_number = 21;
$year = date('Y');
for($day = 0; $day <= 6; $day++)
{
$format = $year. "W" . $week_number.$day;
print $format . "\n";
array_push($days_of_week, date('Y-m-d', strtotime($format)));
}
print_r($days_of_week);
I figured my problem out. Ignoring ISO-8601 week numbers (1-53), I was able to get a range of seven days based on a given date`s week number (0 Sunday - 6 Saturday).
$day = new DateTime($date); // 2015-05-21
$start = $day->modify("- ".$day->format("w")." days"); // - 4 days - 2015-05-17
$end = clone $start;
$end = $start->modify("+ 7 days"); // 2015-05-24 (foreach ignores last day)
$interval = new DateInterval("P1D");
$week = new DatePeriod($start, $interval, $end);
foreach($week as $key => $val) {
$days_of_week[] = date("Y-m-d", strtotime($val->format("Y-m-d")));
}
This method correctly returns an array of seven days, starting on Sunday and ending on Saturday, based on a given date. Thanks to #Rizier123 for the backbone of this answer.
I am trying to query results from last week from Thursday to Wednesday.
Today is the 18th which is Sunday, the first day of the week in PHP terms. My Code is not working because it restarts on Sunday. My IF statement is not working and my week modifier (-1 Week) is not working. Every week should go from thursday to thursday which ends at midnight on Wednesday. The results I am getting is today's results, but it should be going back to just this last thursday, subtracting -1 week, and pulling those results ending just this last thursday.
It should be pulling data between these dates
2015-1-8 thru
2015-1-14
But it's pulling from 2015-1-15 thru 2015-1-21 and not suppose to.
<div class="subtitle">Last Week (12AM Thur to 12AM Thur)</div>
<div class="totamt">$<?php
require_once 'wp-content/themes/azure-basic/connectvars.php';
$dbc = mysqli_connect(CDB_HOST, CDB_USER, CDB_PASSWORD, CDB_NAME);
/* Last Week */
$twoWeeksAgoStart = new DateTime("Thursday last week");
$twoWeeksAgoEnd = new DateTime("Wednesday");
$today = new DateTime("now");
$day = $today->format("1");
if ($day == "Sunday" || $day == "Monday" || $day == "Tuesday" || $day == "Wednesday") {
//This DOES NOT WORK from Sunday to Wednesday
$twoWeeksAgoStart->modify("- 1 week");
$twoWeeksAgoEnd->modify("- 1 week");
} else {
//This DOES actually works on Thursday through Saturday Night
$twoWeeksAgoStart->modify("+7 days");
$twoWeeksAgoEnd->modify("- 1 week");
}
$startdates = $twoWeeksAgoStart->format( 'Y-m-d' );
$enddates = $twoWeeksAgoEnd->format('Y-m-d');
$query = "SELECT SUM(amountoffeeearned) as totalamount FROM commissioninfo WHERE thedate BETWEEN '$startdates' AND '$enddates'";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);
?>
I did some light testing, and I believe this may work for you:
if(date('N') == 4){
$startdates = date("Y-m-d", strtotime("last Thursday"));
$enddates = date("Y-m-d", strtotime("-1 day"));
}else{
$startdates = date("Y-m-d", strtotime("last Thursday -1 week"));
$enddates = date("Y-m-d", strtotime("last Thursday - 1 day"));
}
It checks if today is Thursday and if it is then it uses "last Thursday" and the current day -1 day to get the week. Any other day, it uses last Thursday - 1 week and last Thursday - 1 day to get the timeframe. As if today were say Friday the 23rd, in PHP's mind last Thursday is the day before (the 22nd) and on Thursday last Thursday is the preceding week's Thursday.
Hope this works and helps!
I haven't tested it thoroughly but it might worth the try. Let me know if it works:
$minus = (date('D') !== 'Thu') ? "-1 week" : "";// Thursday check
$startdates = date("Y-m-d", strtotime("$minus last Thursday"));
$enddates = date("Y-m-d", strtotime("last Wednesday"));
Hope it helps.
I have array() of week days to repeat my event.
[days_repeat] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
1,2,3 are the events should be repeated every monday, tuesday, wednesday, but I have also
[start_date] => 2014-04-2
[end_date] => 2014-05-30
As you can see start day isn't the first day to repeat, if it was then was easier, just loop and make dates and break loop, when date is bigger than end date, but maybe you can suggest me some good tactics to achieve this
Days repeat array can contain only week day numbers and so!
First, convert start_date to a timestamp.
Then using php date() function as such :
echo date('w', $your_timestamp);
You get to know what day is the day of first_date, 0 (for Sunday) through 6 (for Saturday).
Then just loop and go through your days checking if they match your array.
Try this:
$daysRepeat = array(1,2,3);
$startDate = '2014-04-02';
$endDate = '2014-05-30';
//Convert to timestamps;
$startDateTstamp = strtotime($startDate);
$endDateTstamp = strtotime($endDate);
//Loop through days between start and end date
$tstamp = $startDateTstamp;
while($tstamp < $endDateTstamp) {
//Calculate numerical representation of week day (1-7)
$weekDay = date('N', $tstamp);
if(in_array($weekDay, $daysRepeat)) {
print date('Y-m-d', $tstamp) . "<br />";
}
$tstamp += (60*60*24);
}
Output:
2014-04-02
2014-04-07
2014-04-08
2014-04-09
2014-04-14
2014-04-15
2014-04-16
2014-04-21
2014-04-22
2014-04-23
2014-04-28
2014-04-29
2014-04-30
2014-05-05
2014-05-06
2014-05-07
2014-05-12
2014-05-13
2014-05-14
2014-05-19
2014-05-20
2014-05-21
2014-05-26
2014-05-27
2014-05-28
if your data represents the days within a week (so first day of the week till the seventh day of the week), than you just need to check the current displayed day, if its the same "daynumber"
eg.
echo (new DateTime())->format("w");
will print
1
for monday
see the docs for more informations.
http://www.php.net/manual/en/function.date.php
so youll need only to check, if the current daynumber is in your repeat array!
You can achieve this with this code:
<?php
$days_repeat = array(
'1', // Monday
'2', // Tuesday
'3', // Wednesday
);
// first set timezone
date_default_timezone_set('UTC');
// Start date
$date = '2014-04-02';
// End date
$end_date = '2014-05-30';
while (strtotime($date) <= strtotime($end_date)) {
// first find out which day of the week it is (0=sunday; 1=monday ... 6=saturday)
$dateWeekDay = date("w", $date);
// convert sunday from 0 to 7 if needed
if ($dateWeekDay == 0) { $dateWeekDay = 7; }
// check if $days_repeat has current day
if (in_array($dateWeekDay, $days_repeat)) {
// do action as this day is in $days_repeat
echo date("Y-m-d"). ' is in $days_repeat';
}
// add +1 day and continue loop
$date = date("Y-m-d", strtotime("+1 day", strtotime($date)));
}
?>
Conveniently, you are representing the day of the week according to the ISO-8601 specification. This means you can use PHP's built-in date() function with no additional translation to your format. That's nice.
Next, you need to figure out how to convert your start_date and end_date into a date format PHP can understand. It looks like mktime() is your best bet here - initialize the time elements to 0 if you don't care about them.
You can now iterate by day and if date("N", $currentDay) is in your array of wanted days, repeat the event on that day (whatever that entails). Here, $currentDay is the looped timestamp you're checking. date("N") returns the same ISO-8601 format day-of-week number as specified in the manual page for date().