Random Set of Dates for Laravel Project - php

This is a Laravel project that I'm attempting to get a random collection of dates between the two dates below. The random dates chosen need to be 6 years apart and be on either a Monday, Thursday or Sunday. I have the dates function below that works for another date range I need however with this situation there's the additional factor of 6 years so I need the additional modification for it and not sure what I need to do to account for it on this situation.
$start = Carbon::parse('First Monday of January 2000');
$nextMonth = Carbon::now()->addMonth();
collect([
'monday' => false,
'thursday' => false,
'sunday' => true
])->flatMap(function ($bool, $day) use ($start, $nextMonth) {
return dates($start, $nextMonth, $day, $bool);
})->sort(function ($a, $b) {
return strtotime($a) - strtotime($b);
})->values()->map(function ($date, $key) {
return factory(Event::class)->create([
'name' => 'Event ' . ($key + 1),
'date' => $date
]);
})->filter(function ($event) {
return $event->date->lt(Carbon::today());
function dates(Carbon $from, Carbon $to, $day, $last = false)
{
$step = $from->copy()->startOfMonth();
$modification = sprintf($last ? 'last %s of next month' : 'next %s', $day);
$dates = [];
while ($step->modify($modification)->lte($to)) {
if ($step->lt($from)) {
continue;
}
$dates[$step->timestamp] = $step->copy();
}
return $dates;
}

If the second date is exactly six years from the first random date:
$second_date = $first_date->diffInYears($first_date->copy()->addYears(6))
From Carbon docs: http://carbon.nesbot.com/docs/#api-difference
Update:
Here is a way of creating an array of dates, based on a start date, where each date is at least six years apart and either a Monday, Thursday or Sunday.
I've left the loop at 20 iterations so you can see the dates generated are different days over the years.
$start = Carbon::parse('First Monday of January 2000');
$dates = array();
for ($i = 1; $i < 20; $i ++)
{
$interval = $i * 6;
if ($start->copy()->addYears($interval)->dayOfWeek === Carbon::MONDAY OR $start->copy()->addYears($interval)->dayOfWeek === Carbon::THURSDAY OR $start->copy()->addYears($interval)->dayOfWeek === Carbon::SUNDAY)
{
$dates[] = $start->copy()->addYears($interval);
} else
{
$dates[] = $start->copy()->addYears($interval)->modify('next monday');
}
}

Related

Calculate n dates of next x days of the week

so I'm trying to build a function that allows me to calculate the dates of the next x days of the week, for example, I want 5 dates from now (02/08/2022), of Tuesday and Thursday, so the output should be:
02/08/2022 - Tu
02/10/2022 - Th
02/15/2022 - Tu
02/17/2022 - Th
02/22/2022 - Tu
I'm not sure how to achieve that, since I want to be able to input various days of the week... Is there a way to do this? My current aproach is this one, but of couse, is not doing what I want, I kinda blocked right now, sorry if the answer is too obvious:
function getNextDates($start_date, $range_weeks, $how_many_dates, $days)
{
$range = 'P' . ($range_weeks * 7) . 'D';
$sd = new DateTimeImmutable($start_date);
$nd = new DateTime($start_date);
$dates_list = array();
$dates_list[0] = array('day' => $sd->format('D'), 'date' => $sd->format('d-m-Y'));
$ind = 1;
$how_many_dates--;
while ($how_many_dates > 0) {
// This in case I want a n weeks space
$nd->add(new DateInterval($range));
for ($i = 0; $i < count($days); $i++) {
if (($i + 1) < count($days)) {
if ($sd->modify($this->nextDay($days[$i])) < $sd->modify($this->nextDay($days[$i + 1]))) {
$nextDate = $nd->modify($this->nextDay($days[$i]));
$dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
$how_many_dates--;
$ind++;
}
} else {
$nextDate = $nd->modify($this->nextDay($days[$i]));
// $sd = $nextDate;
$dates_list[$ind] = array('day' => $nextDate->format('D'), 'date' => $nextDate->format('d-m-Y'));
$how_many_dates--;
$ind++;
}
if ($how_many_dates <= 0) break;
}
}
return $dates_list;
}
Being:
$start_date: 02/08/2022
$range_weeks: 0 // Meaning every week
$how_many_dates: 5
$days: Tuesday, Thursday
I got:
02/08/2022
02/10/2022
02/17/2022
02/24/2022
03/03/2022
Sorry for my amateur code...
Starting from the start date, a day is always added and it is checked whether it is the desired day of the week.
$start = "02/08/2022";
$number = 5;
$weekDays = ['Tue','Thu'];
$dates = [];
for($date = date_create($start); $number > 0; $date->modify('+1 Day')){
$day = $date->format('D');
if(in_array($day,$weekDays)) {
$dates[] = $date->format("d/m/Y");
$number--;
}
}
Result $dates
array (
0 => "08/02/2022",
1 => "10/02/2022",
2 => "15/02/2022",
3 => "17/02/2022",
4 => "22/02/2022",
)

Generate random dates with random times between two dates for selected period and frequency

I have to create a scheduling component that will plan e-mails that need to be sent out. Users can select a start time, end time, and frequency. Code should produce a random moment for every frequency, between start and end time. Outside of office hours.
Paramaters:
User can select a period between 01/01/2020 (the start) and 01/01/2021 (the end). In this case user selects a timespan of one exactly year.
User can select a frequency. In this case user selects '2 months'.
Function:
Code produces a list of datetimes. The total time (one year) is divided by frequency (2 months). We expect a list of 6 datetimes.
Every datetime is a random moment in said frequency (2 months). Within office hours.
Result:
An example result for these paramaters might as follows, with the calculated frequency bounds for clarity:
[jan/feb] 21-02-2020 11.36
[mrt/apr] 04-03-2020 16.11
[mei/jun] 13-05-2020 09.49
[jul-aug] 14-07-2020 15.25
[sep-okt] 02-09-2020 14.09
[nov-dec] 25-12-2020 13.55
--
I've been thinking about how to implement this best, but I can't figure out an elegant solution.
How could one do this using PHP?
Any insights, references, or code spikes would be greatly appreciated. I'm really stuck on this one.
I think you're just asking for suggestions on how to generate a list of repeating (2 weekly) dates with a random time between say 9am and 5pm? Is that right?
If so - something like this (untested, pseudo code) might be a starting point:
$start = new Datetime('1st January 2021');
$end = new Datetime('1st July 2021');
$day_start = 9;
$day_end = 17;
$date = $start;
$dates = [$date]; // Start date into array
while($date < $end) {
$new_date = clone($date->modify("+ 2 weeks"));
$new_date->setTime(mt_rand($day_start, $day_end), mt_rand(0, 59));
$dates[] = $new_date;
}
var_dump($dates);
Steve's anwser seems good, but you should consider 2 additional things
holiday check, in the while after first $new_date line, like:
$holiday = array('2021-01-01', '2021-01-06', '2021-12-25');
if (!in_array($new_date,$holiday))
also a check if date is a office day or a weekend in a similar way as above with working days as an array.
It's kind of crappy code but I think it will work as you wish.
function getDiffInSeconds(\DateTime $start, \DateTime $end) : int
{
$startTimestamp = $start->getTimestamp();
$endTimestamp = $end->getTimestamp();
return $endTimestamp - $startTimestamp;
}
function getShiftData(\DateTime $start, \DateTime $end) : array
{
$shiftStartHour = \DateTime::createFromFormat('H:i:s', $start->format('H:i:s'));
$shiftEndHour = \DateTime::createFromFormat('H:i:s', $end->format('H:i:s'));
$shiftInSeconds = intval($shiftEndHour->getTimestamp() - $shiftStartHour->getTimestamp());
return [
$shiftStartHour,
$shiftEndHour,
$shiftInSeconds,
];
}
function dayIsWeekendOrHoliday(\DateTime $date, array $holidays = []) : bool
{
$weekendDayIndexes = [
0 => 'Sunday',
6 => 'Saturday',
];
$dayOfWeek = $date->format('w');
if (empty($holidays)) {
$dayIsWeekendOrHoliday = isset($weekendDayIndexes[$dayOfWeek]);
} else {
$dayMonthDate = $date->format('d/m');
$dayMonthYearDate = $date->format('d/m/Y');
$dayIsWeekendOrHoliday = (isset($weekendDayIndexes[$dayOfWeek]) || isset($holidays[$dayMonthDate]) || isset($holidays[$dayMonthYearDate]));
}
return $dayIsWeekendOrHoliday;
}
function getScheduleDates(\DateTime $start, \DateTime $end, int $frequencyInSeconds) : array
{
if ($frequencyInSeconds < (24 * 60 * 60)) {
throw new \InvalidArgumentException('Frequency must be bigger than one day');
}
$diffInSeconds = getDiffInSeconds($start, $end);
// If difference between $start and $end is bigger than two days
if ($diffInSeconds > (2 * 24 * 60 * 60)) {
// If difference is bigger than 2 days we add 1 day to start and subtract 1 day from end
$start->modify('+1 day');
$end->modify('-1 day');
// Getting new $diffInSeconds after $start and $end changes
$diffInSeconds = getDiffInSeconds($start, $end);
}
if ($frequencyInSeconds > $diffInSeconds) {
throw new \InvalidArgumentException('Frequency is bigger than difference between dates');
}
$holidays = [
'01/01' => 'New Year',
'18/04/2020' => 'Easter 1st official holiday because 19/04/2020',
'20/04/2020' => 'Easter',
'21/04/2020' => 'Easter 2nd day',
'27/04' => 'Konings',
'04/05' => '4mei',
'05/05' => '4mei',
'24/12' => 'Christmas 1st day',
'25/12' => 'Christmas 2nd day',
'26/12' => 'Christmas 3nd day',
'27/12' => 'Christmas 3rd day',
'31/12' => 'Old Year'
];
[$shiftStartHour, $shiftEndHour, $shiftInSeconds] = getShiftData($start, $end);
$amountOfNotifications = floor($diffInSeconds / $frequencyInSeconds);
$periodInSeconds = intval($diffInSeconds / $amountOfNotifications);
$maxDaysBetweenNotifications = intval($periodInSeconds / (24 * 60 * 60));
// If $maxDaysBetweenNotifications is equals to 1 then we have to change $periodInSeconds to amount of seconds for one day
if ($maxDaysBetweenNotifications === 1) {
$periodInSeconds = (24 * 60 * 60);
}
$dates = [];
for ($i = 0; $i < $amountOfNotifications; $i++) {
$periodStart = clone $start;
$periodStart->setTimestamp($start->getTimestamp() + ($i * $periodInSeconds));
$seconds = mt_rand(0, $shiftInSeconds);
// If $maxDaysBetweenNotifications is equals to 1 then we have to check only one day without loop through the dates
if ($maxDaysBetweenNotifications === 1) {
$interval = new \DateInterval('P' . $maxDaysBetweenNotifications . 'DT' . $seconds . 'S');
$date = clone $periodStart;
$date->add($interval);
$dayIsWeekendOrHoliday = dayIsWeekendOrHoliday($date, $holidays);
} else {
// When $maxDaysBetweenNotifications we have to loop through the dates to pick them
$loopsCount = 0;
$maxLoops = 3; // Max loops before breaking and skipping the period
do {
$day = mt_rand(0, $maxDaysBetweenNotifications);
$periodStart->modify($shiftStartHour);
$interval = new \DateInterval('P' . $day . 'DT' . $seconds . 'S');
$date = clone $periodStart;
$date->add($interval);
$dayIsWeekendOrHoliday = dayIsWeekendOrHoliday($date, $holidays);
// If the day is weekend or holiday then we have to increment $loopsCount by 1 for each loop
if ($dayIsWeekendOrHoliday === true) {
$loopsCount++;
// If $loopsCount is equals to $maxLoops then we have to break the loop
if ($loopsCount === $maxLoops) {
break;
}
}
} while ($dayIsWeekendOrHoliday);
}
// Adds the date to $dates only if the day is not a weekend day and holiday
if ($dayIsWeekendOrHoliday === false) {
$dates[] = $date;
}
}
return $dates;
}
$start = new \DateTime('2020-12-30 08:00:00', new \DateTimeZone('Europe/Sofia'));
$end = new \DateTime('2021-01-18 17:00:00', new \DateTimeZone('Europe/Sofia'));
$frequencyInSeconds = 86400; // 1 day
$dates = getScheduleDates($start, $end, $frequencyInSeconds);
var_dump($dates);
You have to pass $start, $end and $frequencyInSeconds as I showed in example and then you will get your random dates. Notice that I $start and $end must have hours in them because they are used as start and end hours for shifts. Because the rule is to return a date within a shift time only in working days. Also you have to provide frequency in seconds - you can calculate them outside the function or you can change it to calculate them inside. I did it this way because I don't know what are your predefined periods.
This function returns an array of \DateTime() instances so you can do whatever you want with them.
UPDATE 08/01/2020:
Holidays now are part of calculation and they will be excluded from returned dates if they are passed when you are calling the function. You can pass them in d/m and d/m/Y formats because of holidays like Easter and in case when the holiday is on weekend but people will get additional dayoff during the working week.
UPDATE 13/01/2020:
I've made updated code version to fix the issue with infinite loops when $frequencyInSeconds is shorter like 1 day. The new code used few functions getDiffInSeconds, getShiftData and dayIsWeekendOrHoliday as helper methods to reduce code duplication and cleaner and more readable code

PHP Carbon date difference with only working days

I'm trying to get difference between two dates in human format but only with working days. Here is my actual code:
$start = '2018-09-13 09:30:00';
$end = '2018-10-16 16:30:00';
$from = Carbon::parse($start);
$to = Carbon::parse($end);
$weekDay = $from->diffInWeekdays($to);
$human = $to->diffForHumans($from, true, false, 6);
var_dump($weekDay); //24
var_dump($human); // 1 month 3 days 7 hours
diffForHumans is perfect for my needs but I can't find any way of filtering like diffInDaysFiltered
What I would like to achieve is to get this result: 24 days 7 hours because we only have 24 working days
I tried a preg_replace first to replace 3 days by $weekDay result but if we have a month before it's incorrect and I have: 1 month 24 days 7 hours
Is there any solution for my problem ?
Here is the answer thanks to imbrish
I need to use the cascade factor to define:
How many hours is a day
How many days is a week
How many days is a month
Then with the diffFiltered I can only select weekday and working hours. You can also add a filter on public holiday thanks to macro
CarbonInterval::setCascadeFactors(array(
'days' => array(10, 'hours'),
'weeks' => array(5, 'days'),
'months' => array(20, 'days'),
));
$resolution = CarbonInterval::hour();
$start = Carbon::parse('2017-07-13 11:00');
$end = Carbon::parse('2017-07-17 18:00');
$hours = $start->diffFiltered($resolution, function ($date) {
return $date->isWeekday() && $date->hour >= 8 && $date->hour < 18;
}, $end);
$interval = CarbonInterval::hours($hours)->cascade();
echo $interval->forHumans(); // 2 days 7 hours
Here is the macro part:
Carbon::macro('isHoliday', function ($self = null) {
// compatibility chunk
if (!isset($self) && isset($this)) {
$self = $this;
}
// Put your array of holidays here
return in_array($self->format('d/m'), [
'25/12', // Christmas
'01/01', // New Year
]);
});
Then simply add && !$date->isHoliday() inside the diffFiltered
The above-mentioned answers are good correct. But there are some other ways also with carbon.
$startDate = Carbon::create(2017, 4, 4);
$endDate = Carbon::create(2017, 4, 18);
$no_of_days = $startDate->diffInDaysFiltered(function(Carbon $date) {
return !$date->isSunday();
}, $endDate);
Some useful functions of Carbon
$dt->isMonday();
$dt->isTuesday();
$dt->isWednesday();
$dt->isThursday();
$dt->isFriday();
$dt->isSaturday();
$dt->isSunday();
$dt->isDayOfWeek(Carbon::SATURDAY); // is a saturday
For more information go to https://carbon.nesbot.com/docs/
Ok, The solution works, but i had some problem with more complex time calculation, so i figured out another solution with while cycle
Carbon::macro('isHoliday', function ($self = null) {
// compatibility chunk
if (!isset($self) && isset($this)) {
$self = $this;
}
// Put your array of holidays here
return in_array($self->format('d/m'), [
'23/12',
'24/12',
'25/12',
'26/12',
'27/12',
'28/12',
'29/12',
'30/12',
'31/12',
'01/01',
'02/01',
'03/01',
'04/01',
'05/01',
'06/01',
'07/01',
]);
});
$end = Carbon::now();
$hours = 160;
while($hours > 0) {
if ($end->hour < 9 || $end->hour >= 18 || $end->hour == 13 || $end->isWeekend() || $end->isHoliday()) {
$end->addHour();
} else {
$end->addHour();
$hours--;
}
}
Debugbar::addMessage($end);

Count weekend days between range dates from array in php

I'm trying to calculate the number of weekend days between dates from the array below:
$dates[] = array ( 'DateFrom' => '2015-07-10', 'DateTo' => '2015-07-10', 'DateFrom' => '2015-07-12', 'DateTo' => '2015-07-12', 'DateFrom'=> '2015-07-17', 'DateTo'=> '2015-07-19') ;
The result must return number of weekend days between these dates
Between these dates are 3 days of weekend (2015-07-12, 2015-07-18, and 2015-07-19).
Anyone have any idea?
You need to loop through from start date to end date and in each iteration need to check for day (sat/sun)
Algo :
$weekends = 0;
$startDate = strtotime($startDate);
$endDate = strtotime($endDate);
while($startDate<$endDate) {
//"N" gives ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)
$day = date("N",$startDate);
if($day == 6 || $day == 7) {
$weekends++;
}
$startDate = 24*60*60 ; //1 day
}
Firstly, if you're defining your array exactly as written, you're duplicating keys and four of those items will be overwritten. But assuming we're just looking at the pairs. Pass the FromDate and ToDate from each pair to this function and add up all the return values.
function getWeekends ($fromDate, $toDate) {
$from = strtotime($fromDate);
$to = strtotime($toDate);
$diff = floor(abs($to-$from)/(60*60*24)); // total days betwixt
$num = floor($diff/7) * 2; // number of weeks * 2
$fromNum = date("N", $from);
$toNum = date("N", $to);
if ($toNum < $fromNum)
$toNum += 7;
// get range of day numbers
$dayarr = range($fromNum, $toNum);
// check if there are any weekdays in that range
$num += count(array_intersect($dayarr, array(6, 7, 13)));
return $num;
}
There may be a more elegant solution.
To be used on each pair of dates:
function getWeekendDays($startDate, $endDate)
{
$weekendDays = array(6, 7);
$period = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1D'),
new DateTime($endDate)
);
$weekendDaysCount = 0;
foreach ($period as $day) {
if (in_array($day->format('N'), $weekendDays)) {
$weekendDaysCount++;
}
}
return $weekendDaysCount;
}

Calculate week of a month [duplicate]

So I have a script that returns the number of weeks in a particular month and year. How can I take a specific day from that month and determine if it is part of week 1,2,3,4 or 5 of that month?
The most frustrating thing I have ever tried to get working - but here it is!
<?php
/**
* Returns the amount of weeks into the month a date is
* #param $date a YYYY-MM-DD formatted date
* #param $rollover The day on which the week rolls over
*/
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "00");
$elapsed = ($timestamp - $first) / $daylen;
$weeks = 1;
for ($i = 1; $i <= $elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover)) $weeks ++;
}
return $weeks;
}
//
echo getWeeks("2011-06-11", "sunday"); //outputs 2, for the second week of the month
?>
Edit: so much for "single line" - needed variables to avoid recomputation with the conditional. Tossed in a default argument while I was at it.
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = date('W', $when); // note that ISO weeks start on Monday
$firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
Please note that weekOfMonth(strtotime('Oct 31, 2011')); will return 6; some rare months have 6 weeks in them, contrary to OP's expectation. January 2017 is another month with 6 ISO weeks - Sunday the 1st falls in the last year's week, since ISO weeks start on Monday.
For starshine531, to return a 0 indexed week of the month, change the return 1 + to return 0 + or return (int).
For Justin Stayton, for weeks starting on Sunday instead of Monday I would use strftime('%U' instead of date('W', as follows:
function weekOfMonth($when = null) {
if ($when === null) $when = time();
$week = strftime('%U', $when); // weeks start on Sunday
$firstWeekOfMonth = strftime('%U', strtotime(date('Y-m-01', $when)));
return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}
For this version, 2017-04-30 is now in week 6 of April, while 2017-01-31 is now in week 5.
public function getWeeks($timestamp)
{
$maxday = date("t",$timestamp);
$thismonth = getdate($timestamp);
$timeStamp = mktime(0,0,0,$thismonth['mon'],1,$thismonth['year']); //Create time stamp of the first day from the give date.
$startday = date('w',$timeStamp); //get first day of the given month
$day = $thismonth['mday'];
$weeks = 0;
$week_num = 0;
for ($i=0; $i<($maxday+$startday); $i++) {
if(($i % 7) == 0){
$weeks++;
}
if($day == ($i - $startday + 1)){
$week_num = $weeks;
}
}
return $week_num;
}
Hello all i have been struggling for the whole day trying to figure this code out, i finally figured it out so i thought i would share it with you all.
all you need to do is put a time stamp into the function and it will return the week number back to you.
thanks
there is a problem with this method. if the passing date (Lets say 2012/01/01 which is a Sunday) and "$rollover" day is "Sunday", then this function will return 2. where its actually is 1'st week. i think i have fixed it in following function.
please add comments to make it better.
function getWeeks($date, $rollover)
{
$cut = substr($date, 0, 8);
$daylen = 86400;
$timestamp = strtotime($date);
$first = strtotime($cut . "01");
$elapsed = (($timestamp - $first) / $daylen)+1;
$i = 1;
$weeks = 0;
for($i==1; $i<=$elapsed; $i++)
{
$dayfind = $cut . (strlen($i) < 2 ? '0' . $i : $i);
$daytimestamp = strtotime($dayfind);
$day = strtolower(date("l", $daytimestamp));
if($day == strtolower($rollover))
{
$weeks++;
}
}
if($weeks==0)
{
$weeks++;
}
return $weeks;
}
This is a solution based on sberry's mathematical solution but using the PHP DateTime class instead.
function week_of_month($date) {
$first_of_month = new DateObject($date->format('Y/m/1'));
$day_of_first = $first_of_month->format('N');
$day_of_month = $date->format('j');
return floor(($day_of_first + $day_of_month - 1) / 7) + 1;
}
Just Copy and Past the code and pass month and year.
e.g month=04 year=2013.
That's exactly what You Need.
$mm= $_REQUEST['month'];
$yy= $_REQUEST['year'];
$startdate=date($yy."-".$mm."-01") ;
$current_date=date('Y-m-t');
$ld= cal_days_in_month(CAL_GREGORIAN, $mm, $yy);
$lastday=$yy.'-'.$mm.'-'.$ld;
$start_date = date('Y-m-d', strtotime($startdate));
$end_date = date('Y-m-d', strtotime($lastday));
$end_date1 = date('Y-m-d', strtotime($lastday." + 6 days"));
$count_week=0;
$week_array = array();
for($date = $start_date; $date <= $end_date1; $date = date('Y-m-d', strtotime($date. ' + 7 days')))
{
$getarray=getWeekDates($date, $start_date, $end_date);
echo "<br>";
$week_array[]=$getarray;
echo "\n";
$count_week++;
}
// its give the number of week for the given month and year
echo $count_week;
//print_r($week_array);
function getWeekDates($date, $start_date, $end_date)
{
$week = date('W', strtotime($date));
$year = date('Y', strtotime($date));
$from = date("Y-m-d", strtotime("{$year}-W{$week}+1"));
if($from < $start_date) $from = $start_date;
$to = date("Y-m-d", strtotime("{$year}-W{$week}-6"));
if($to > $end_date) $to = $end_date;
$array1 = array(
"ssdate" => $from,
"eedate" => $to,
);
return $array1;
// echo "Start Date-->".$from."End Date -->".$to;
}
for($i=0;$i<$count_week;$i++)
{
$start= $week_array[$i]['ssdate'];
echo "--";
$week_array[$i]['eedate'];
echo "<br>";
}
OUTPUT:
week( 0 )=>2013-03-01---2013-03-02
week( 1 )=>2013-03-03---2013-03-09
week( 2 )=>2013-03-10---2013-03-16
week( 3 )=>2013-03-17---2013-03-23
week( 4 )=>2013-03-24---2013-03-30
week( 5 )=>2013-03-31---2013-03-31
I think I found an elegant solution
$time = time(); // or whenever
$week_of_the_month = ceil(date('d', $time)/7);
For a Monday-Sunday (ISO 8601) week (or, if you simply don't care), you can do this in one line:
function get_week_of_month($date) {
return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}
(Source)
For anything else, (e.g. a Sunday-Saturday week), you just need to tweak $date inside the function:
function get_week_of_month($date) {
$date += 86400; //For weeks starting on Sunday
return date('W', $date) - date('W', strtotime(date("Y-m-01", $date))) + 1;
}
(Thanks to these guys/gals)
NOTE: You may run into some issues at the end of the year (e.g. around 12/31, 1/1, etc.). Read more here.
This is the snippet that I made to fulfill my requirements for the same. Hope this will help you.
function getWeek($timestamp) {
$week_year = date('W',$timestamp);
$week = 0;//date('d',$timestamp)/7;
$year = date('Y',$timestamp);
$month = date('m',$timestamp);
$day = date('d',$timestamp);
$prev_month = date('m',$timestamp) -1;
if($month != 1 ){
$last_day_prev = $year."-".$prev_month."-1";
$last_day_prev = date('t',strtotime($last_day_prev));
$week_year_last_mon = date('W',strtotime($year."-".$prev_month."-".$last_day_prev));
$week_year_first_this = date('W',strtotime($year."-".$month."-1"));
if($week_year_first_this == $week_year_last_mon){
$week_diff = 0;
}
else{
$week_diff = 1;
}
if($week_year ==1 && $month == 12 ){
// to handle December's last two days coming in first week of January
$week_year = 53;
}
$week = $week_year-$week_year_last_mon + 1 +$week_diff;
}
else{
// to handle first three days January coming in last week of December.
$week_year_first_this = date('W',strtotime($year."-01-1"));
if($week_year_first_this ==52 || $week_year_first_this ==53){
if($week_year == 52 || $week_year == 53){
$week =1;
}
else{
$week = $week_year + 1;
}
}
else{
$week = $week_year;
}
}
return $week;
}
This is probably not a good way to do this but it's my first thought and I'm really tired.
Put all your dates into an array. The date object must have a day name (Monday). Create a method that searches the array and when ever you hit a Sunday you add 1 to a week counter. Once you find the date you're looking for return the week counter. That is the week the day falls in of the year. For the week in the month you have to reset the week counter every time you get to the last day in each month.
Here comes two liner:
function getWeekOfMonth(DateTime $date) {
$firstDayOfMonth = new DateTime($date->format('Y-m-1'));
return ceil(($firstDayOfMonth->format('N') + $date->format('j') - 1) / 7);
}
And Wtower's solutions doesn't work 100% properly.
Thought I'd share my function as well. This returns an array of weeks. Every week is an array with weeks day (0..6) as key and months day (1..31) as value.
Function assumes that week starts with Sunday.
Enjoy!
function get_weeks($year, $month){
$days_in_month = date("t", mktime(0, 0, 0, $month, 1, $year));
$weeks_in_month = 1;
$weeks = array();
//loop through month
for ($day=1; $day<=$days_in_month; $day++) {
$week_day = date("w", mktime(0, 0, 0, $month, $day, $year));//0..6 starting sunday
$weeks[$weeks_in_month][$week_day] = $day;
if ($week_day == 6) {
$weeks_in_month++;
}
}
return $weeks;
}
My 5 cents:
/**
* calculate number of weeks in a particular month
*/
function weeksInMonth($month=null,$year=null){
if( null==($year) ) {
$year = date("Y",time());
}
if(null==($month)) {
$month = date("m",time());
}
// find number of days in this month
$daysInMonths = date('t',strtotime($year.'-'.$month.'-01'));
$numOfweeks = ($daysInMonths%7==0?0:1) + intval($daysInMonths/7);
$monthEndingDay= date('N',strtotime($year.'-'.$month.'-'.$daysInMonths));
$monthStartDay = date('N',strtotime($year.'-'.$month.'-01'));
if($monthEndingDay<$monthStartDay){
$numOfweeks++;
}
return $numOfweeks;
}
I create this function, from brazil :) I hope it is useful
function weekofmonth($time) {
$firstday = 1;
$lastday = date('j',$time);
$lastdayweek = 6; //Saturday
$week = 1;
for ($day=1;$day<=$lastday;$day++) {
$timetmp = mktime(0, 0, 0, date('n',$time), $day, date('Y',$time));
if (date('N',$timetmp) == $lastdayweek) {
$week++;
}
}
if (date('N',$time)==$lastdayweek) {
$week--;
}
return $week;
}
$time = mktime(0, 0, 0, 9, 30, 2014);
echo weekofmonth($time);
I found a easy way to determine what week of the month today is in, and it would be a small change to have it work on any other date. I'm adding my two cents in here as I think my way is much more compact then the methods listed.
$monthstart = date("N",strtotime(date("n/1/Y")));
$date =( date("j")+$monthstart ) /7;
$ddate= floor( $date );
if($ddate != date) {$ddate++;}
and $ddate contains the week number you could modify it like so
function findweek($indate)
{
$monthstart = date("N",strtotime(date("n/1/Y",strtotime($indate))));
$date =( date("j",strtotime($indate))+$monthstart ) /7;
$ddate= floor( $date );
if($ddate != $date) {$ddate++;}
return $ddate;
}
and it would return what week of the month any date you give it is.
what it does is first find the number of days from the start of the week to the first of the month. then adds that on to the current date then divides the new date by 7 and that will give you how many weeks have passed since the start of the month, including a decimal place for the part of the the current week that has passed. so what I do next is round down that number, then compare the rounded down version to the original if the two match your at the end of the week so it's already in the number. if they don't then just add one to the rounded down number and voila you have the current week number.
Srahul07's solution works perfectly... If you abide by the Monday-Sunday week system! Here in 'murica, non-business folk tend to go by Sunday-Saturday being a week, so May 1, 2011 is week 1 and May 2, 2011 is still week 1.
Adding the following logic to the bottom of his function, right before it returns $week will convert this to a Sunday -> Monday system:
if (!date('w',strtotime("$year-$month-01")) && date('w',$timestamp))
$week--;
elseif (date('w',strtotime("$year-$month-01")) && !date('w',$timestamp))
$week++;
After alot of efoort i found the solution
<?php
function getWeeks($month,$year)
{
$month = intval($month); //force month to single integer if '0x'
$suff = array('st','nd','rd','th','th','th'); //week suffixes
$end = date('t',mktime(0,0,0,$month,1,$year)); //last date day of month: 28 - 31
$start = date('w',mktime(0,0,0,$month,1,$year)); //1st day of month: 0 - 6 (Sun - Sat)
$last = 7 - $start; //get last day date (Sat) of first week
$noweeks = ceil((($end - ($last + 1))/7) + 1); //total no. weeks in month
$output = ""; //initialize string
$monthlabel = str_pad($month, 2, '0', STR_PAD_LEFT);
for($x=1;$x<$noweeks+1;$x++)
{
if($x == 1)
{
$startdate = "$year-$monthlabel-01";
$day = $last - 6;
}
else
{
$day = $last + 1 + (($x-2)*7);
$day = str_pad($day, 2, '0', STR_PAD_LEFT);
$startdate = "$year-$monthlabel-$day";
}
if($x == $noweeks)
{
$enddate = "$year-$monthlabel-$end";
}
else
{
$dayend = $day + 6;
$dayend = str_pad($dayend, 2, '0', STR_PAD_LEFT);
$enddate = "$year-$monthlabel-$dayend";
}
$j=1;
if($j--)
{
$k=getTotalDate($startdate,$enddate);
$j=1;
}
$output .= "Week ".$xyz." week -> Start date=$startdate End date=$enddate <br />";
}
return $output;
}
if(isset($_POST) && !empty($_POST)){
$month = $_POST['m'];
$year = $_POST['y'];
echo getWeeks($month,$year);
}
?>
<form method="post">
M:
<input name="m" value="" />
Y:
<input name="y" value="" />
<input type="submit" value="go" />
</form>
I really liked #michaelc's answer. However, I got stuck on a few points. It seemed that every time Sunday rolled around, there was an offset of one. I think it has to do with what day of the week is the start of the week. In any case, here is my slight alteration to it, expanded a bit for readability:
function wom(\DateTime $date) {
// The week of the year of the current month
$cw = date('W', $date->getTimestamp());
// The week of the year of the first of the given month
$fw = date('W',strtotime(date('Y-m-01',$date->getTimeStamp())));
// Offset
$o = 1;
// If it is a Saturday, offset by two.
if( date('N',$date->getTimestamp()) == 7 ) {
$o = 2;
}
return $cw -$fw + $o;
}
So if the date is Nov. 9, 2013...
$cw = 45
$fw = 44
and with the offset of 1, it correctly returns 2.
If the date is Nov. 10, 2013, $cw and $fw are the same as before, but the offset is 2, and it correctly returns 3.
function get_week_of_month( $timestamp )
{
$week_of_month = 0;
$month = date( 'j', $timestamp );
$test_month = $month;
while( $test_month == $month )
{
$week_of_month++;
$timestamp = strtotime( '-1 week', $timestamp );
$test_month = date( 'j', $timestamp );
}
return $week_of_month;
}
I found this online:
http://kcwebprogrammers.blogspot.de/2009/03/current-week-in-month-php.html
He has a very simple solution which seems to work fine for me.
$currentWeek = ceiling((date("d") - date("w") - 1) / 7) + 1;
So for example:
$now = strtotime("today");
$weekOfMonth = ceil((date("d", $now) - date("w", $now) - 1) / 7) + 1;
you can use W in newer php versions. http://php.net/manual/en/function.date.php
i have used it like so:
function getWeek($date) {
$month_start=strtotime("1 ".date('F Y',$date));
$current_date=strtotime(date('j F Y',$date));
$month_week=date("W",$month_start);
$current_week=date("W",$current_date);
return ($current_week-$month_week);
}//0 is the week of the first.
Short and foolproof:
// Function accepts $date as a string,
// Returns the week number in which the given date falls.
// Assumed week starts on Sunday.
function wom($date) {
$date = strtotime($date);
$weeknoofday = date('w', $date);
$day = date('j', $date);
$weekofmonth = ceil(($day + (7-($weeknoofday+1))) / 7);
return $weekofmonth;
}
// Test
foreach (range(1, 31) as $day) {
$test_date = "2015-01-" . str_pad($day, 2, '0', STR_PAD_LEFT);
echo "$test_date - ";
echo wom($test_date) . "\n";
}
I use this simple function:
function weekNumberInMonth($timestampDate)
{
$firstDayOfMonth = strtotime(date('01-M-Y 00:00:00', $timestampDate));
$firstWeekdayOfMonth = date( 'w', $firstDayOfMonth);
$dayNumberInMonth = date('d', $timestampDate);
$weekNumberInMonth = ceil(($dayNumberInMonth + $firstWeekdayOfMonth) / 7);
return $weekNumberInMonth;
}
if I understand correct, the question is how to identify what number of week within a month of a specific day... I was looking for similar solution. I used some ideas of above answers to develop my own solution. Hope it can be helpful for somebody. If Yes, then UpVote my answer.
function week_number_within_month($datenew){
$year = date("Y",strtotime($datenew));
$month = date("m",strtotime($datenew));
// find number of days in this month
$daysInMonths = date('t',strtotime($year.'-'.$month.'-01'));
$numOfweeks = ($daysInMonths%7==0?0:1) + intval($daysInMonths/7);
$monthEndingDay= date('N',strtotime($year.'-'.$month.'-'.$daysInMonths));
$monthStartDay = date('N',strtotime($year.'-'.$month.'-01'));
if($monthEndingDay<$monthStartDay){
$numOfweeks++;
}
$date=date('Y/m/d', strtotime($year.'-'. $month.'-01'));
$week_array=Array();
for ($i=1; $i<=$numOfweeks; $i++){ /// create an Array of all days of month separated by weeks as a keys
$max = 7;
if ($i ==1){ $max = 8 - $monthStartDay;}
if ($i == $numOfweeks){ $max = $monthEndingDay;}
for ($r=1; $r<=$max; $r++){
$week_array[$i][]=$date;
$date = date('Y/m/d',strtotime($date . "+1 days"));
}
}
$new_datenew = date('Y/m/d', strtotime($datenew));
$week_result='';
foreach ($week_array as $key => $val){ /// finding what week number of my date from week_array
foreach ($val as $kr => $value){
if ($new_datenew == $value){
$week_result = $key;
}
}
}
return $week_result;
}
print week_number_within_month('2016-09-15');
function getWeekOfMonth(\DateTime $date)
{
$firstWeekdayOfMonth = new DateTime("first weekday 0 {$date->format('M')} {$date->format('Y')}");
$offset = $firstWeekdayOfMonth->format('N')-1;
return intval(($date->format('j') + $offset)/7)+1;
}
/**
* In case of Week we can get the week of year. So whenever we will get the week of the month then we have to
* subtract the until last month weeks from it will give us the current month week.
*/
$dateComponents = getdate();
if($dateComponents['mon'] == 1)
$weekOfMonth = date('W', strtotime($dateComponents['year'].'-'.$dateComponents['mon'].'-'.$dateComponents['mday']))-1; // We subtract -1 to map it to the array
else
$weekOfMonth = date('W', strtotime($dateComponents['year'].'-'.$dateComponents['mon'].'-'.$dateComponents['mday']))-date('W', strtotime($dateComponents['year'].'-'.$dateComponents['mon'].'-01'));
Using Carbon:
$date = Carbon::now();
$d1 = $date->startOfMonth();
$d2 = $date->endOfMonth();
$weeks = $d1->diffInWeeks($d2);
If you clearly want to separate a month into 4 Weeks, you can use this function.
This is helpful, if you want
"the first monday of month"
"the third thursday of month" etc.
Here we go
/**
* This Calculates (and returns) the week number within a month, based on date('j') day of month.
* This is useful, if you want to have (for instance) the first Thu in month, regardless of date
* #param $Timestamp
* #return float|int
*/
function getWeekOfMonth($Timestamp)
{
$DayOfMonth=date('j', $Timestamp); // Day of the month without leading zeros 0-31
if($DayOfMonth>21) return 4;
if($DayOfMonth>14) return 3;
if($DayOfMonth>7) return 2;
return 1;
}
From carbon:
return (int) ceil((new Datetime())->format('d') / 7);
As simple as possible :)
Python: Number of the Week in a Month
This is a worked example in Python - should be simple to convert.

Categories