Repeatable events php - php

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().

Related

Function calculation date (Except Sunday day, july and August month)

Hello I am looking to do a date calculation function. I have a first date for example 2018-06-29 and I would like to add 30 days to this date, if by adding 30 days I fall on a Sunday I would like to withdraw -1 day so fall on a Saturday, the date recover from the calculation will be 2018-07-28 and so on ....
If the date falls in the month of July, we will postpone for the month of June, and if we fall in August, we will postpone the month of September.
Currently I get the first date like this
Array
(
[date_delivery] => 2018-06-27
)
And I prepare the calculation function
public function calculDate($dateDelivery)
{
ddd($dateDelivery);
}
Thank you for your help.
function calcDate($date) {
$newDate = strtotime('+1 month',$date);
$day = day('D',$newDate);
if ($day == 'Sun') $newDate = strtotime('-1 day', $newDate);
}

Laravel 5.4 get every day of the current week using Carbon

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"
]

How to get special day of week and list of weekdays using bootstrap datepicker in PHP

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

PHP date increment by month not exceeding last day of month?

I want same day of month for each of the months that fall between start date and end date. Its just that if the month of the day is not valid for a particular month, you want last day of that month. is there any script?. What is have done is.
$startdate='2010-01-30';
$enddate='2011-01-30';
while ($startdate <= $enddate)
{
echo date('Y-m-d', $startdate ) . "\n";
$startdate = strtotime('+1 month', $startdate);/// for case of feb 28 days last date it should disply as it skips it
}
Expected out put:
For input $startdate='2012-01-30'; $enddate='2013-12-30' Result should be like this ==>
_2012-12-30_
2013-01-30
**2013-02-28**
2013-03-30
2013-04-30
2013-05-30
2013-06-30
2013-07-30
2013-08-30
2013-09-30
2013-10-30
2013-11-30
_2013-12-30_
Loop using for and adding $i months to the start date instead of constantly adding one month to the running value. This way it won't jump to 28th (or 29th) day because of february starting from march.

PHP DateTime::modify adding and subtracting months

I've been working a lot with the DateTime class and recently ran into what I thought was a bug when adding months. After a bit of research, it appears that it wasn't a bug, but instead working as intended. According to the documentation found here:
Example #2 Beware when adding or
subtracting months
<?php
$date = new DateTime('2000-12-31');
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
$date->modify('+1 month');
echo $date->format('Y-m-d') . "\n";
?>
The above example will output:
2001-01-31
2001-03-03
Can anyone justify why this isn't considered a bug?
Furthermore does anyone have any elegant solutions to correct the issue and make it so +1 month will work as expected instead of as intended?
Why it's not a bug:
The current behavior is correct. The following happens internally:
+1 month increases the month number (originally 1) by one. This makes the date 2010-02-31.
The second month (February) only has 28 days in 2010, so PHP auto-corrects this by just continuing to count days from February 1st. You then end up at March 3rd.
How to get what you want:
To get what you want is by: manually checking the next month. Then add the number of days next month has.
I hope you can yourself code this. I am just giving what-to-do.
PHP 5.3 way:
To obtain the correct behavior, you can use one of the PHP 5.3's new functionality that introduces the relative time stanza first day of. This stanza can be used in combination with next month, fifth month or +8 months to go to the first day of the specified month. Instead of +1 month from what you're doing, you can use this code to get the first day of next month like this:
<?php
$d = new DateTime( '2010-01-31' );
$d->modify( 'first day of next month' );
echo $d->format( 'F' ), "\n";
?>
This script will correctly output February. The following things happen when PHP processes this first day of next month stanza:
next month increases the month number (originally 1) by one. This makes the date 2010-02-31.
first day of sets the day number to 1, resulting in the date 2010-02-01.
Here is another compact solution entirely using DateTime methods, modifying the object in-place without creating clones.
$dt = new DateTime('2012-01-31');
echo $dt->format('Y-m-d'), PHP_EOL;
$day = $dt->format('j');
$dt->modify('first day of +1 month');
$dt->modify('+' . (min($day, $dt->format('t')) - 1) . ' days');
echo $dt->format('Y-m-d'), PHP_EOL;
It outputs:
2012-01-31
2012-02-29
This may be useful:
echo Date("Y-m-d", strtotime("2013-01-01 +1 Month -1 Day"));
// 2013-01-31
echo Date("Y-m-d", strtotime("2013-02-01 +1 Month -1 Day"));
// 2013-02-28
echo Date("Y-m-d", strtotime("2013-03-01 +1 Month -1 Day"));
// 2013-03-31
echo Date("Y-m-d", strtotime("2013-04-01 +1 Month -1 Day"));
// 2013-04-30
echo Date("Y-m-d", strtotime("2013-05-01 +1 Month -1 Day"));
// 2013-05-31
echo Date("Y-m-d", strtotime("2013-06-01 +1 Month -1 Day"));
// 2013-06-30
echo Date("Y-m-d", strtotime("2013-07-01 +1 Month -1 Day"));
// 2013-07-31
echo Date("Y-m-d", strtotime("2013-08-01 +1 Month -1 Day"));
// 2013-08-31
echo Date("Y-m-d", strtotime("2013-09-01 +1 Month -1 Day"));
// 2013-09-30
echo Date("Y-m-d", strtotime("2013-10-01 +1 Month -1 Day"));
// 2013-10-31
echo Date("Y-m-d", strtotime("2013-11-01 +1 Month -1 Day"));
// 2013-11-30
echo Date("Y-m-d", strtotime("2013-12-01 +1 Month -1 Day"));
// 2013-12-31
My solution to the problem:
$startDate = new \DateTime( '2015-08-30' );
$endDate = clone $startDate;
$billing_count = '6';
$billing_unit = 'm';
$endDate->add( new \DateInterval( 'P' . $billing_count . strtoupper( $billing_unit ) ) );
if ( intval( $endDate->format( 'n' ) ) > ( intval( $startDate->format( 'n' ) ) + intval( $billing_count ) ) % 12 )
{
if ( intval( $startDate->format( 'n' ) ) + intval( $billing_count ) != 12 )
{
$endDate->modify( 'last day of -1 month' );
}
}
I agree with the sentiment of the OP that this is counter-intuitive and frustrating, but so is determining what +1 month means in the scenarios where this occurs. Consider these examples:
You start with 2015-01-31 and want to add a month 6 times to get a scheduling cycle for sending an email newsletter. With the OP's initial expectations in mind, this would return:
2015-01-31
2015-02-28
2015-03-31
2015-04-30
2015-05-31
2015-06-30
Right away, notice that we are expecting +1 month to mean last day of month or, alternatively, to add 1 month per iteration but always in reference to the start point. Instead of interpreting this as "last day of month" we could read it as "31st day of next month or last available within that month". This means that we jump from April 30th to May 31st instead of to May 30th. Note that this is not because it is "last day of month" but because we want "closest available to date of start month."
So suppose one of our users subscribes to another newsletter to start on 2015-01-30. What is the intuitive date for +1 month? One interpretation would be "30th day of next month or closest available" which would return:
2015-01-30
2015-02-28
2015-03-30
2015-04-30
2015-05-30
2015-06-30
This would be fine except when our user gets both newsletters on the same day. Let's assume that this is a supply-side issue instead of demand-side We're not worried that the user will be annoyed with getting 2 newsletters in the same day but instead that our mail servers can't afford the bandwidth for sending twice as many newsletters. With that in mind, we return to the other interpretation of "+1 month" as "send on the second to last day of each month" which would return:
2015-01-30
2015-02-27
2015-03-30
2015-04-29
2015-05-30
2015-06-29
Now we've avoided any overlap with the first set, but we also end up with April and June 29th, which certainly does match our original intuitions that +1 month simply should return m/$d/Y or the attractive and simple m/30/Y for all possible months. So now let's consider a third interpretation of +1 month using both dates:
Jan. 31st
2015-01-31
2015-03-03
2015-03-31
2015-05-01
2015-05-31
2015-07-01
Jan. 30th
2015-01-30
2015-03-02
2015-03-30
2015-04-30
2015-05-30
2015-06-30
The above has some issues. February is skipped, which could be a problem both supply-end (say if there is a monthly bandwidth allocation and Feb goes to waste and March gets doubled up on) and demand-end (users feel cheated out of Feb and perceive the extra March as attempt to correct mistake). On the other hand, notice that the two date sets:
never overlap
are always on the same date when that month has the date (so the Jan. 30 set looks pretty clean)
are all within 3 days (1 day in most cases) of what might be considered the "correct" date.
are all at least 28 days (a lunar month) from their successor and predecessor, so very evenly distributed.
Given the last two sets, it would not be difficult to simply roll back one of the dates if it falls outside of the actual following month (so roll back to Feb 28th and April 30th in the first set) and not lose any sleep over the occasional overlap and divergence from the "last day of month" vs "second to last day of month" pattern. But expecting the library to choose between "most pretty/natural", "mathematical interpretation of 02/31 and other month overflows", and "relative to first of month or last month" is always going to end with someone's expectations not being met and some schedule needing to adjust the "wrong" date to avoid the real-world problem that the "wrong" interpretation introduces.
So again, while I also would expect +1 month to return a date that actually is in the following month, it is not as simple as intuition and given the choices, going with math over the expectations of web developers is probably the safe choice.
Here's an alternative solution that is still as clunky as any but I think has nice results:
foreach(range(0,5) as $count) {
$new_date = clone $date;
$new_date->modify("+$count month");
$expected_month = $count + 1;
$actual_month = $new_date->format("m");
if($expected_month != $actual_month) {
$new_date = clone $date;
$new_date->modify("+". ($count - 1) . " month");
$new_date->modify("+4 weeks");
}
echo "* " . nl2br($new_date->format("Y-m-d") . PHP_EOL);
}
It's not optimal but the underlying logic is : If adding 1 month results in a date other than the expected next month, scrap that date and add 4 weeks instead. Here are the results with the two test dates:
Jan. 31st
2015-01-31
2015-02-28
2015-03-31
2015-04-28
2015-05-31
2015-06-28
Jan. 30th
2015-01-30
2015-02-27
2015-03-30
2015-04-30
2015-05-30
2015-06-30
(My code is a mess and wouldn't work in a multi-year scenario. I welcome anyone to rewrite the solution with more elegant code so long as the underlying premise is kept intact, i.e. if +1 month returns a funky date, use +4 weeks instead.)
In conjunction with shamittomar's answer, it could then be this for adding months "safely":
/**
* Adds months without jumping over last days of months
*
* #param \DateTime $date
* #param int $monthsToAdd
* #return \DateTime
*/
public function addMonths($date, $monthsToAdd) {
$tmpDate = clone $date;
$tmpDate->modify('first day of +'.(int) $monthsToAdd.' month');
if($date->format('j') > $tmpDate->format('t')) {
$daysToAdd = $tmpDate->format('t') - 1;
}else{
$daysToAdd = $date->format('j') - 1;
}
$tmpDate->modify('+ '. $daysToAdd .' days');
return $tmpDate;
}
I made a function that returns a DateInterval to make sure that adding a month shows the next month, and removes the days into the after that.
$time = new DateTime('2014-01-31');
echo $time->format('d-m-Y H:i') . '<br/>';
$time->add( add_months(1, $time));
echo $time->format('d-m-Y H:i') . '<br/>';
function add_months( $months, \DateTime $object ) {
$next = new DateTime($object->format('d-m-Y H:i:s'));
$next->modify('last day of +'.$months.' month');
if( $object->format('d') > $next->format('d') ) {
return $object->diff($next);
} else {
return new DateInterval('P'.$months.'M');
}
}
This is an improved version of Kasihasi's answer in a related question. This will correctly add or subtract an arbitrary number of months to a date.
public static function addMonths($monthToAdd, $date) {
$d1 = new DateTime($date);
$year = $d1->format('Y');
$month = $d1->format('n');
$day = $d1->format('d');
if ($monthToAdd > 0) {
$year += floor($monthToAdd/12);
} else {
$year += ceil($monthToAdd/12);
}
$monthToAdd = $monthToAdd%12;
$month += $monthToAdd;
if($month > 12) {
$year ++;
$month -= 12;
} elseif ($month < 1 ) {
$year --;
$month += 12;
}
if(!checkdate($month, $day, $year)) {
$d2 = DateTime::createFromFormat('Y-n-j', $year.'-'.$month.'-1');
$d2->modify('last day of');
}else {
$d2 = DateTime::createFromFormat('Y-n-d', $year.'-'.$month.'-'.$day);
}
return $d2->format('Y-m-d');
}
For example:
addMonths(-25, '2017-03-31')
will output:
'2015-02-28'
I found a shorter way around it using the following code:
$datetime = new DateTime("2014-01-31");
$month = $datetime->format('n'); //without zeroes
$day = $datetime->format('j'); //without zeroes
if($day == 31){
$datetime->modify('last day of next month');
}else if($day == 29 || $day == 30){
if($month == 1){
$datetime->modify('last day of next month');
}else{
$datetime->modify('+1 month');
}
}else{
$datetime->modify('+1 month');
}
echo $datetime->format('Y-m-d H:i:s');
Here is an implementation of an improved version of Juhana's answer in a related question:
<?php
function sameDateNextMonth(DateTime $createdDate, DateTime $currentDate) {
$addMon = clone $currentDate;
$addMon->add(new DateInterval("P1M"));
$nextMon = clone $currentDate;
$nextMon->modify("last day of next month");
if ($addMon->format("n") == $nextMon->format("n")) {
$recurDay = $createdDate->format("j");
$daysInMon = $addMon->format("t");
$currentDay = $currentDate->format("j");
if ($recurDay > $currentDay && $recurDay <= $daysInMon) {
$addMon->setDate($addMon->format("Y"), $addMon->format("n"), $recurDay);
}
return $addMon;
} else {
return $nextMon;
}
}
This version takes $createdDate under the presumption that you are dealing with a recurring monthly period, such as a subscription, that started on a specific date, such as the 31st. It always takes $createdDate so late "recurs on" dates won't shift to lower values as they are pushed forward thru lesser-valued months (e.g., so all 29th, 30th or 31st recur dates won't eventually get stuck on the 28th after passing thru a non-leap-year February).
Here is some driver code to test the algorithm:
$createdDate = new DateTime("2015-03-31");
echo "created date = " . $createdDate->format("Y-m-d") . PHP_EOL;
$next = sameDateNextMonth($createdDate, $createdDate);
echo " next date = " . $next->format("Y-m-d") . PHP_EOL;
foreach(range(1, 12) as $i) {
$next = sameDateNextMonth($createdDate, $next);
echo " next date = " . $next->format("Y-m-d") . PHP_EOL;
}
Which outputs:
created date = 2015-03-31
next date = 2015-04-30
next date = 2015-05-31
next date = 2015-06-30
next date = 2015-07-31
next date = 2015-08-31
next date = 2015-09-30
next date = 2015-10-31
next date = 2015-11-30
next date = 2015-12-31
next date = 2016-01-31
next date = 2016-02-29
next date = 2016-03-31
next date = 2016-04-30
$ds = new DateTime();
$ds->modify('+1 month');
$ds->modify('first day of this month');
If you just want to avoid skipping a month you can perform something like this to get the date out and run a loop on the next month reducing the date by one and rechecking until a valid date where $starting_calculated is a valid string for strtotime (i.e. mysql datetime or "now"). This finds the very end of the month at 1 minute to midnight instead of skipping the month.
$start_dt = $starting_calculated;
$next_month = date("m",strtotime("+1 month",strtotime($start_dt)));
$next_month_year = date("Y",strtotime("+1 month",strtotime($start_dt)));
$date_of_month = date("d",$starting_calculated);
if($date_of_month>28){
$check_date = false;
while(!$check_date){
$check_date = checkdate($next_month,$date_of_month,$next_month_year);
$date_of_month--;
}
$date_of_month++;
$next_d = $date_of_month;
}else{
$next_d = "d";
}
$end_dt = date("Y-m-$next_d 23:59:59",strtotime("+1 month"));
Extension for DateTime class which solves problem of adding or subtracting months
https://gist.github.com/66Ton99/60571ee49bf1906aaa1c
If using strtotime() just use $date = strtotime('first day of +1 month');
I needed to get a date for 'this month last year' and it becomes unpleasant quite quickly when this month is February in a leap year. However, I believe this works... :-/ The trick seems to be to base your change on the 1st day of the month.
$this_month_last_year_end = new \DateTime();
$this_month_last_year_end->modify('first day of this month');
$this_month_last_year_end->modify('-1 year');
$this_month_last_year_end->modify('last day of this month');
$this_month_last_year_end->setTime(23, 59, 59);
$month = 1; $year = 2017;
echo date('n', mktime(0, 0, 0, $month + 2, -1, $year));
will output 2 (february). will work for other months too.
$current_date = new DateTime('now');
$after_3_months = $current_date->add(\DateInterval::createFromDateString('+3 months'));
For days:
$after_3_days = $current_date->add(\DateInterval::createFromDateString('+3 days'));
Important:
The method add() of DateTime class modify the object value so after calling add() on a DateTime Object it returns the new date object and also it modify the object it self.
you can actually do it with just date() and strtotime() as well. For example to add 1 month to todays date:
date("Y-m-d",strtotime("+1 month",time()));
if you are wanting to use the datetime class thats fine too but this is just as easy. more details here
$date = date('Y-m-d', strtotime("+1 month"));
echo $date;

Categories