How to add date + 6 month but exclude Sundays using PHP - php

I am creating a scheduler script that if I executed a task today my next task will be 6 months from today (Semi-Annual) but my problem is people has no activity on Sundays so it must be adjusted on Monday instead.
How can I add 6 month to today's date but exclude Sundays, I am using PHP and able to add 6 months using below code so far.
My code is this.
<?php echo date('Y-m-d', strtotime('+6 months'));?>

Here's the answer: https://stackoverflow.com/a/12365635/6557808
Provides more than you're asking for and is pretty clear.

Here is a small function to it. Just pass from and end date
<?php
function number_of_working_days($from, $to) {
$workingDays = [1, 2, 3, 4, 5, 6]; # date format = N (1 = Monday, ...)
$from = new DateTime($from);
$to = new DateTime($to);
$to->modify('+1 day');
$interval = new DateInterval('P1D');
$periods = new DatePeriod($from, $interval, $to);
$days = 0;
foreach ($periods as $period) {
if (!in_array($period->format('N'), $workingDays)) continue;
$days++;
}
return $days;
}
echo number_of_working_days('2017-05-06', '2017-05-08');
?>

Complete Answer is here:--
function daysToAdd($startDate,$endDate)
{
$count=0;
While($startDate!=$endDate){
$lpcnt=0;
$begin = new DateTime($startDate);
$end = new DateTime($endDate);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt ){
if($dt->format( "l" )=='Sunday'){
$count++;
$lpcnt++;
}
}
$day = date('D', strtotime($endDate));
if($day=='Sun'){
$count=$count+1;
$lpcnt=$lpcnt+1;
}
$startDate=date('Y-m-d', strtotime($endDate . ' +1 day'));
$endDate=date('Y-m-d', strtotime($endDate . ' +'.$lpcnt.' day'));
if($startDate!=$endDate){
daysToAdd($startDate,$endDate);
}else{
if(date('D', strtotime($startDate))=='Sun') {
$count=$count+1;
break;
}
}
}
return $count;
}
$currentDate=date('Y-m-d');
$postSixMonth=date('Y-m-d', strtotime("+5 months"));
$daysToadd=daysToAdd($currentDate,$postSixMonth);
$requiredDate=date('Y-m-d', strtotime($postSixMonth . ' +'.$daysToadd.' days'));
echo $requiredDate;exit;

As stated in the PHP.net date() documentation you can check for a specific day number.
So, using that knowledge you can either:
if (date("w", strtotime("+6 months")) == 0) {
echo date("Y-m-d", strtotime("+6 months +1 days"));
}
else {
echo date("Y-m-d", "+6 months");
}
or something in the lines of Bilal Ahmed's answer using a switch
switch (date("w", strtotime("+6 months")) == 0) {
case 0: // Sunday
echo date("Y-m-d", strtotime("+6 months +1 days"));
break;
case 1: // Monday
case 2: // Tuesday
case 3: // Wednesday
case 4: // Thursday
case 5: // Friday
case 6: // Saturday
echo date("Y-m-d", "+6 months");
break;
}
which might be better if there is something to do for every different day as date() will not be executed every time you perform a case. (Note: I did not compare speeds)
EDIT: oneliner based on the comment of blokish on the askers post
echo date("w", strtotime("+6 months")) == 0 ? date("Y-m-d", "+6 months +1 days") : date("Y-m-d", "+6 months");

Related

How to count date from a day only without have any specific date in a week

I want to detect how to detect if the day is in the specific settings that I save.
I already save the settings
$checkday = "Sunday";
$period = "48"; // this in hours
So I need to check if today in this week is Sunday + 48 hours after (means Tuesday) then run a function.
I already make these code
$starttimer = date('Y-m-d 00:00:00', strtotime($checkday));
$endtimer = date('Y-m-d H:i:s', strtotime('+' . $period . ' hour', strtotime(date('Y-m-d 00:00:00'))));
if(time() >= strtotime($starttimer) && time() <= strtotime($endtimer)){
// this should run a function
}
This code is working if today is Sunday, but the problem is when today is Monday it will detect next Week Monday. I need it to check from this week Sunday + 48 hours after then run function.
The conclusion is I want to run the function on every week start from Sunday + 48 hours after.
Thanks for reading my problem, hope someone can help me.
I think you need get day of this week.
because if checkday = "Monday" then $starttimer will return Monday of next week.
<?php
$checkday = 'Monday';
$period = 48;
$day_this_week = "$checkday this week";
$starttimer = date('Y-m-d 00:00:00', strtotime($day_this_week));
$endtimer = date('Y-m-d H:i:s', strtotime('+' . $period . ' hour', strtotime(date('Y-m-d 00:00:00'))));
var_dump($starttimer);//string(19) "2022-09-12 00:00:00"
You can use the flexibility of strtotime to find the time of the last occurance of $checkDay. You also need to check to see that today is the check day and run in that condition as well.
<?php
$checkDay = 'Sunday';
$period = 48;
$isCheckDay = date('w', strtotime($checkDay)) === date('w');
$start = strtotime('last ' . $checkDay);
$end = strtotime(date('Y-m-d', $start) . ' +' . $period . ' hours');
$now = time();
if ($isCheckDay || ($now >= $start && $now <= $end)) {
echo 'run function';
}
It is not necessary to work with timestamps. Datetime objects can be directly compared. This makes the code easier to read.
$checkday = "Sunday";
$period = "2 Days";
$dtStart = date_create('Tomorrow')->modify('last '.$checkday);
$dtEnd = (clone $dtStart)->modify($period);
/* Use 'Now' instead of 'Today' in the following line
* if the time periods can also be fractions of days.
*/
$dtToDay = date_create('today');
if($dtToDay >= $dtStart AND $dtToDay < $dtEnd){
echo 'run function';
}
else {
echo 'do nothing';
}
$dtStart is always the last $checkday weekday before tomorrow. A time in hours can also be entered for $period, for example "48 hours".
Demo: https://3v4l.org/5d2Xt
You can use below code for fulfill your requirement...
<?php
$checkday = "Sunday";
$period = "48"; // this in hours
echo date('l', strtotime($checkday. ' + '.$period.' hours'));
?>

Find date of after 2 months using php

When i have current date is in "31/12/2017". I need to find date of after 2 months that means its February. When its february i need to get as "29/2/2018". But When we use below code i got "03/03/2018". Can you please help me to solve this task,
Here i added my PHP code,
$xmasDay = new DateTime('2017-12-31 + 2 month');
echo $xmasDay->format('Y-m-d');
please try this
<?php
function add_month($date_str, $months)
{
$date = new DateTime($date_str);
// We extract the day of the month as $start_day
$start_day = $date->format('j');
// We add 1 month to the given date
$date->modify("+{$months} month");
// We extract the day of the month again so we can compare
$end_day = $date->format('j');
if ($start_day != $end_day)
{
// The day of the month isn't the same anymore, so we correct the date
$date->modify('last day of last month');
}
return $date->format('Y-m-d');
}
$result = add_month('2017-12-31', 2);
echo $result
calculate from first of the month, then use date t
$orginal = '2017-12-31';
$orginal = explode('-', $orginal);
$originalDate = strtotime($orginal[0] . '-' . $orginal[1] . '-01 00:00:00');
$newDate = strtotime('+2 month', $originalDate);
echo date('Y-m-t', $newDate);
// or
$date = new DateTime();
$date->setTimestamp($newDate);
echo $date->format('Y-m-t');

PHP - How to calculate one month or one year later

I'd like to calculate next billing date of Recurly plan in PHP.
There are 2 types of billing cycle: yearly | monthly.
I tried to use DateTime and DateInterval classes, but didn't get expected results.
<?php
$referenceTime = new \DateTime('2016-01-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-03-02 00:00:00.000000'
Adding one month to the 31st of Januray gives me the second of March and not the 29th (or 28th) of February as I would expect.
The same for the 31st of August:
<?php
$referenceTime = new \DateTime('2016-08-31');
$oneMonthLater = $referenceTime->modify('+1 month');
var_dump($oneMonthLater);
// public 'date' => string '2016-10-01 00:00:00.000000'
If yearly, I expect Feb 29, 2016 + 1 year => Feb 28, 2017
Thanks.
Try this, if date > 28 use last day of next month else use +1 month
$get_date = strtotime("31-01-2016");
$dt = explode("-",$get_date);
$dt = $dt[0];
var_dump(($dt > 28) ? date("d-m-Y", strtotime("31-01-2016 last day of next month")) : date("d-m-Y", strtotime("31-01-2016 +1 month")));
DEMO
You can call modify with PHP's DateTime object to calculate the next date relative to the current date. The following code shows how you would do it with your specific situation.
$next_bill_date = new DateTime();
switch($plan_interval_unit) {
case "year":
$next_bill_date->modify("last day of next month");
break;
case "month":
$next_bill_date->modify("last day of this month next year");
break;
}
May be something like that:
if (date('d') !== date('d', strtotime('+1 month'))
date ('Y-m-d H:i:s', strtotime('last day of next month'));
if (date('d') !== date('d', strtotime('+1 year'))
date ('Y-m-d H:i:s', strtotime('last day of this month next year'));
You can use PHP inbuilt strtotime() function
// One month from today
$date = date('Y-m-d', strtotime('+1 month'));
// One month from a specific date
$date = date('Y-m-d', strtotime('+1 month', strtotime('2016-12-06')));
function get_next_billing_date($now, $type, $format = 'Y-m-d')
{
$date = new DateTime($now);
$y = $date->format("Y");
$m = $date->format("m");
$d = $date->format("d");
if ($type == 'year') {
$y++;
if ($m == 2 && $d == 29) {
$d = 28;
}
} else if ($type == 'month') {
if ($m == 12) {
$y++;
$m = 1;
} else {
$m++;
}
$first_date = sprintf("%04d-%02d-01", $y, $m);
$last_day_of_next_month = date('t', strtotime($first_date));
if ($d > $last_day_of_next_month) {
$d = $last_day_of_next_month;
}
} else {
// not supported
return false;
}
$date->setDate($y, $m, $d);
return $date->format($format);
}

php get today tomorrow and next day but ignore weekends

How can I get the current day, tomorrow and next day in PHP but ignore weekends?
I have already tried this code, but it will include Saturday and Sunday.
array(
'todayDate' => date('d/m/Y')
'tomorrowDate' => date('d/m/Y', strtotime(' +1 day')),
'nextDay' => date('l', strtotime(' +2 day'))
)
Thanks.
Use Weekday(s) with strtotime
date('l', strtotime(' +2 Weekdays'));
Fiddle
This finds the next weekday from a specific date (not including Saturday or Sunday):
echo date('Y-m-d', strtotime('2011-04-05 +2 Weekday'));
You could also do it with a date variable of course:
$myDate = '2011-04-05';
echo date('Y-m-d', strtotime($myDate . ' +2 Weekday'));
Try this, Get date between two date without weekdays(Saturday and Sunday).
$startdate = '10-06-2015';
$endDate = '17-06-2015' ;
$Workingdays = getdateBettwoDate($startdate,$endDate);
print_r($Workingdays);
function getdateBettwoDate($startdate,$enddate)
{
$start = new DateTime($startdate);
$end = new DateTime($enddate);
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($start, $interval, $end);
$x=0;
$a=array();
foreach ($period as $dt)
{
$temp=$dt->format("l d-m-Y");
$ArTemp=explode(' ',$temp);
if($ArTemp[0]=='Saturday' || $ArTemp[0]=='Sunday'){
}else{
$a[$x]=$ArTemp[1];
$x++ ;
}
}
$a[$x]=date('l', strtotime( $enddate))." ".$enddate;
return $a ;
}

Dates in php Sunday and Saturday?

i have one date.
example : $date='2011-21-12';
data format :yyyy-dd-mm;
IF date is Saturday or Sunday.
if Saturday add 2 day to the given date.
if Sunday add 1 day to the given date.
?
In a single line of code:
if (date('N', $date) > 5) $nextweekday = date('Y-m-d', strtotime("next Monday", $date));
If the day of week has a value greater than 5 (Monday = 1, Sat is 6 and Sun is 7) set $nextweekday to the YYYY-MM-DD value of the following Monday.
Editing to add, because the date format may not be accepted, you would need to reformat the date first. Add the following lines above my code:
$pieces = explode('-', $date);
$date = $pieces[0].'-'.$pieces[2].'-'.$pieces[1];
This will put the date in Y-m-d order so that strtotime can recognize it.
You can use the date and strtotime functions for this, like so:
$date = strtotime('2011-12-21');
$is_saturday = date('l', $date) == 'Saturday';
$is_sunday = date('l', $date) == 'Sunday';
if($is_saturday) {
$date = strtotime('+2 days', $date);
} else if($is_sunday) {
$date = strtotime('+1 days', $date);
}
echo 'Date is now ' . date('Y-m-d H:i:s', $date);
What about this:
$date='2011-21-12';
if (date("D", strtotime($date)) == "Sat"){
$new_date = date("Y-m-d", strtotime("+ 2 days",$date);
}
else if (date("D", strtotime($date)) == "Sun"){
$new_date = date("Y-m-d", strtotime("+ 1 day",$date);
}
The DateTime object can be really helpful for anything like this.
In this case.
$date = DateTime::createFromFormat('Y-d-m', '2011-21-12');
if ($date->format('l') == 'Sunday')
$date->modify('+1 day');
elseif ($date->format('l') == 'Saturday')
$date->modify('+2 days');
If you want to get the date back in that format.
$date = $date->format('Y-d-m');
$date = '2011-21-12'
$stamp = strtotime($date);
$day = date("l", $stamp);
if ($day == "Saturday"){
$stamp = $stamp + (2*+86400);
}elseif($day == "Sunday"){
$stamp = $stamp + 86400;
}
echo date("Y-d-m", $stamp);
The only reason i can think why this wouldnt work is strtotime not recognising that data format...
For sundays date('w',$date) will return 0, so the simplest test code is:
if(!date('w',strtotime($date)) { ... } //sunday
I just subtracted the difference from 8 an added it to the days.
if(date('N', strtotime($date)) >= 6) {
$n = (8 - date("N",strtotime($date)));
$date = date("Y-m-d", strtotime("+".$n." days");
}

Categories