How to get $date + 5 to exclude weekends? - php

I have some pages that require a date to be set in the future (either 2 or 5 days as set by a variable).
This date needs to be only counting Monday - Friday, excluding weekends.
What I have so far ($tts is the variable of 2 or 5 depending on page);
$Today = date('N:m:y');
$NewDate = date('l \t\h\e jS \o\f F',strtotime($Today) + (24*3600*$tts));
$businessDays = [1, 2, 3, 4, 5];
echo $NewDate;
This works without excluding weekend days.
I have tried to use the $businessDays but I'm unsure of how I can use this to count what days are between $Today and $NewDate

Try:
$plusFive = strtotime( '+5 weekday' );
$plusFive = date( 'Y-m-d', $plusFive );
strtotime also takes a second parameter which could be the base for the +5.

Try this code.
It should pick a weekday $tts days ahead.
$Today = date('N:m:y');
$NewDate = date('l \t\h\e jS \o\f F',strtotime($Today . '+' . $tts .' weekdays'));
echo $NewDate;
https://3v4l.org/4SX0m

A DateTime option:
<?php
$start = new DateTime();
date_add( $start, date_interval_create_from_date_string( '5 weekdays' ) );
echo $start->format( 'd-m-Y' );

You could check if its weekend and then add 2 days for Saturday and Sunday like this:
$busDays = 3;
$day = date("w");
if( $day > 2 && $day <= 5 ) { /* if between Wed and Fri */
$day += 2; /* add 2 more days for weekend */
}
$day += $busDays;

Related

Find week number dates with php

is there a solution to find the start and the end date for a specific week number. Example:
If i enter $week = 5, i want to get 2016-03-28 - 2016-04-03. I need only for the current year.
I think what you're looking for is strtotime and date.
<?php
$year = 2016;
$week = 1;
$a = strtotime('January 1 ' . $year);
$b = date('N', $a) - 1;
$c = $a;
$a += (7 - $b) * 86400;
if($week > 1) {
$start = $a + (($week - 2) * 604800);
$end = $start + ($b ? 518400 : 604800);
}
else {
$start = $c;
$end = $a - 86400;
}
echo date('l jS \of F Y', $start);
echo '<br />';
echo date('l jS \of F Y', $end);
Friday 1st of January 2016
Sunday 3rd of January 2016
As a function with some validation. This version will even keep the last week of the year short, like the first week, if the last week rolls into the next year. Returns false if the week does not fall within the year:
<?php
function weekdays($week, $year = false) {
$week = floor($week);
if($week < 0 || $week > 53)
return false;
if($year == false)
$year = date('Y');
$a = strtotime('January 1 ' . $year);
$b = date('N', $a) - 1;
$c = $a;
$a += (7 - $b) * 86400;
if($week > 1) {
$a += (($week - 2) * 604800);
$b = $a + ($b ? 518400 : 604800);
return
date('Y', $a) == $year
? array(
'first' => $a,
'last' =>
date('Y', $b) > $year
? $b - (8 - date('N', $b)) * 86400
: $b
) : false;
}
else
return array('first' => $c, 'last' => $a - 86400);
}
$week = weekdays(14, 2016);
echo date('l jS \of F Y', $week['first']);
echo '<br />';
echo date('l jS \of F Y', $week['last']);
Monday 28th of March 2016
Sunday 3rd of April 2016
You can do this with DateTime:
$year = 2016;
$week = 13;
$date = new DateTime();
$date->setISODate($year, $week);
$start = $date->format('Y-m-d');
$end = $date->modify('+6 days')->format('Y-m-d');
echo 'Week start: '. $start , "\n"; // 2016-03-28
echo 'Week end: '. $end , "\n"; // 2016-04-03
You could use PHP relative datetime functions (http://php.net/manual/en/datetime.formats.relative.php) like:
//date_default_timezone_set('Europe/Amsterdam');
$date = new DateTime();
$date->modify('2016W5'); //First day of week 5 of 2016
$date->modify('2016W5 +6 days'); //Last day of week 5 of 2016
Or build your own function:
function week_start_date($wk_num, $yr, $first = 1, $format = 'F d, Y')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
$sStartDate = week_start_date($week_number, $year);
$sEndDate = date('F d, Y', strtotime('+6 days', strtotime($sStartDate)));
Extracted from here: Finding First day of week via php
If i enter $week = 5, i want to get 2016-03-28 - 2016-04-03.
So, I think you want monday and sunday of 5th week of march.
To obtain this, I create a simple function that require a date string (YYYY-MM-DD) and the week number. The function create a DateTime object from given string, then modify it in the first day of month, then retrieve first day of date week and add $week -1 weeks. At this point we have the first day (monday) of desired week. We clone this date to $end and we add to it 6 days.
Function returns an object with $start and $end dates as properties, obtained casting an array created by compact():
function monthWeek( $date, $week )
{
$start = new DateTime( $date );
$start->modify( 'first day of this month' );
$start->modify( '-'.($start->format( 'w' )-1).' days' );
$start->modify( '+'.($week-1).' weeks' );
$end = clone $start;
$end->modify( '+6 days' );
return (object) compact( 'start', 'end' );
}
Calling above function with a casual day of march:
$week = monthWeek( '2016-03-25', 5 );
echo $week->start->format( 'l, Y-m-d' );
echo " => ";
echo $week->end->format( 'l, Y-m-d' );
we obtain this:
Monday, 2016-03-28 => Sunday, 2016-04-03
You can use the function also for retrieve year-based week, using a day of january as first arguments:
$week = monthWeek( '2016-01-25', 14 );
echo $week->start->format( 'l, Y-m-d' );
echo " => ";
echo $week->end->format( 'l, Y-m-d' );
will output:
Monday, 2016-03-28 => Sunday, 2016-04-03
phpFiddle demo

Calculate Saturday following up to user form input date

I have made a form where users can select a date from a calander. It wil return d/m/Y, 14/05/2013.
What i need is the Saturday following up that date 14/05/2013 what will be 18/05/2013
The date field is called: $_POST['field_3']
I have been struggling with strtotime but with no succes
I have done sofar:
<?php
$today = $_POST['field_3'];
$date = strtotime('d/m/Y','next Saturday', $today);
$initialString = date('m/d/Y', $date);
$end = date('m/d/Y', strtotime( 'next saturday 11:59 pm', $date));
echo $today ."<br>";
echo $initialString . ' - ' . $end;
?>
which returns:
14/05/2013
01/01/1970 - 01/03/1970
Very basic, but this can help :
<?php
$year = 2013; // use substr() (or other stuff) to set these variables
$month = 5;
$day = 14;
$newDate = mktime(0, 0, 0, $month, $day, $year); // creates a date with previous variables
$dayOfWeek = date('w', $newDate); // get the weekday number; 0 = sunday, ..., 6 = saturday
$numberOfDaysTillNextSaturday = (6 == $dayOfWeek) ? 7 : (6 - $dayOfWeek); // how many days until next saturday ? If saturday = 6, otherwise = (Saturday - weekday)
$nextSaturdayDate = $newDate + (86400 * $numberOfDaysTillNextSaturday); // creates a new date corresponding to next saturday
$nextSaturdayString = date("d/m/Y", $nextSaturdayDate); // formats the new date as (day)/(month)/(year)
echo $nextSaturdayString; // echoes the string
?>

php - find date for same day of week for last year

So, in PHP i'm trying to return a date value for last year based on the same day of week.
EX: (Monday) 2011-12-19 inputted should return (Monday) 2010-12-20.
I was just doing it simply by -364 but then that was failing on leap years. I came across another function :
$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);
$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;
$oldDate = strtotime("$dayDiff days",$oldDate);
echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);
however, that is failing when you try to input a Sunday date, as it does a 0 (sunday) minus 6 (saturday of last year date), and returns with a value T-6. IE inputting 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.
I'm kind of stumped to find a good solution in php that will work for leap years and obviously all days of the week.
Any suggestions?
Thanks!
How about this, using PHP's DateTime functionality:
$date = new DateTime('2011-12-25'); // make a new DateTime instance with the starting date
$day = $date->format('l'); // get the name of the day we want
$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day); // from this point, go to the next $day
echo $date->format('Ymd'), "\n"; // ouput the date
$newDate = '2011-12-19';
date_default_timezone_set('UTC');
$newDate = strtotime($newDate);
$oldDate = strtotime('last year', $newDate);
$oldDate = strtotime(date('l', $newDate), $oldDate);
$dateFormat = 'Y-m-d l w W';
echo "This date: ", date($dateFormat, $newDate), "\n";
echo "Old date : ", date($dateFormat, $oldDate);
That gives:
This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
Use strtotime() to get a date, for the same week last year.
Use the format {$year}-W{$week}-{$weekday}, like this:
echo date("Y-m-d", strtotime("2010-W12-1"));
And you can do that for as long back you wan't:
<?php
for($i = 2011; $i > 2000; $i--)
echo date("Y-m-d", strtotime($i."-W12-1"));
?>
Make it easier :)
echo date('Y-m-d (l, W)').<br/>;
echo date('Y-m-d (l, W)', strtotime("-52 week"));
Edit: I forgot to write output: :)
2015-05-06 (Wednesday, 19)
2014-05-07 (Wednesday, 19)
<?php
$date = "2020-01-11";
$newdate = date("Y-m-d",strtotime ( '-1 year' , strtotime ( $date ) )) ;
echo $newdate;
?>
ref https://www.nicesnippets.com/blog/how-to-get-previous-year-from-date-in-php

Increase current date by 5 days

$date = date('Y-m-d',current_time('timestamp', 0));
How do I change $date to $date + 5 days?
PHP version is 5.2.
This code doesn't work:
$date_cur = date('Y-m-d',current_time('timestamp', 0));
echo $date_cur . ' <br>';
$date_cur_plus = date($date_cur, strtotime('+5 days'));
echo $date_cur_plus;
Gives me:
2011-11-29
2011-11-29
$date = date('Y-m-d', strtotime('+5 days'));
You could use mktime() using the timestamp.
Something like:
$date = date('Y-m-d', mktime(0, 0, 0, date('m'), date('d') + 5, date('Y')));
Using strtotime() is faster, but my method still works and is flexible in the event that you need to make lots of modifications. Plus, strtotime() can't handle ambiguous dates.
Edit
If you have to add 5 days to an already existing date string in the format YYYY-MM-DD, then you could split it into an array and use those parts with mktime().
$parts = explode('-', $date);
$datePlusFive = date(
'Y-m-d',
mktime(0, 0, 0, $parts[1], $parts[2] + 5, $parts[0])
// ^ Month ^ Day + 5 ^ Year
);
Object oriented Style:
<?php
$date = new DateTime('now');
$date->add(new DateInterval('P5D'));
echo $date->format('Y-m-d') . "\n";
?>
Procedural Style:
<?php
$date = date_create('2016-01-01');
date_add($date, date_interval_create_from_date_string('5 days'));
echo date_format($date, 'Y-m-d');
?>
Use strtotime:
$date = date('Y-m-d', strtotime('+5 days'));
$dateplus5 = date('Y-m-d', strtotime('+5 days'));
For specific date:
$date = '2011-11-01';
$date_plus = date('Y-m-d', strtotime($date.'+5 days'));
echo $date.'<br>'.$date_plus;
It will be give :
2011-11-01
2011-11-06
You can use
strtotime(“+5 days”)
to get the current date plus 5 days or
$targetDate = date($date, strtotime(’+5 days’));
strtotime() is very nice. It allows you to do the following:
$startDate = 'now'; // or choose a certain date you want/have
$startDate = '2013-02-14';
$intervals = array(
'',
'+ 5 days',
'+ 31 days',
'+ 3 months',
'+ 2 years + 2 days'
);
foreach($intervals as $interval) {
$combinedDate = $startDate . ' ' . $interval;
var_dump($combinedDate . ' => ' date('Y-m-d', strtotime($combinedDate)));
}
with a result:
now => 1360334498 = 2013-02-08
now + 5 days => 1360766498 = 2013-02-13
now + 31 days => 1363012898 = 2013-03-11
now + 3 months => 1368020498 = 2013-05-08
now + 2 years + 2 days => 1423579298 = 2015-02-10
or:
2013-02-14 => 1360792800 = 2013-02-14
2013-02-14 + 5 days => 1361224800 = 2013-02-19
2013-02-14 + 31 days => 1363471200 = 2013-03-17
2013-02-14 + 3 months => 1368478800 = 2013-05-14
2013-02-14 + 2 years + 2 days => 1424037600 = 2015-02-16
I used this:
$date = strtotime("+1 day", strtotime("2007-02-28"));
echo date("Y-m-d", $date);
It's working now.
Did not supposed to be like this?
$date_cur = date('Y-m-d', current_time('timestamp', 0));
echo $date_cur . ' <br>';
$date_cur_plus = date('Y-m-d', strtotime('+5 days', current_time('timestamp', 0) ) );
echo $date_cur_plus;
if the date is already exists, you can used this code :
$tartDate = date("m/d/Y", strtotime("+1 Day", strtotime($Date)));

Get date for monday and friday for the current week (PHP)

How can I get the date for monday and friday for the current week?
I have the following code, but it fails if current day is sunday or saturday.
$current_day = date("N");
$days_to_friday = 5 - $current_day;
$days_from_monday = $current_day - 1;
$monday = date("Y-m-d", strtotime("- {$days_from_monday} Days"));
$friday = date("Y-m-d", strtotime("+ {$days_to_friday} Days"));
Best solution would be:
$monday = date( 'Y-m-d', strtotime( 'monday this week' ) );
$friday = date( 'Y-m-d', strtotime( 'friday this week' ) );
These strtotime inputs work very well:
strtotime( "next monday" );
strtotime( "previous monday" );
strtotime( "today" );
strtotime( "next friday" );
strtotime( "previous friday" );
All you need to do is to wrap the logic inside some if statements.
This question needs a DateTime answer:-
/**
* #param String $day
* #return DateTime
*/
function getDay($day)
{
$days = ['Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 'Friday' => 5, 'Saturday' => 6, 'Sunday' => 7];
$today = new \DateTime();
$today->setISODate((int)$today->format('o'), (int)$today->format('W'), $days[ucfirst($day)]);
return $today;
}
Usage:
var_dump(getDay('Monday')->format('l dS F Y'));
var_dump(getDay('Friday')->format('l dS F Y'));
Output:
string 'Monday 30th September 2013' (length=26)
string 'Friday 04th October 2013' (length=24)
See it working
i use :
$first_week_date = date('d F Y', strtotime('next Monday -1 week', strtotime('this sunday')));
$last_week_date = date('d F Y', strtotime('next Monday -1 week + 4 days', strtotime('this sunday')));
This really depends on how you define a week but I came up with this function that will give you the date for the nearest "monday" or "friday" (or any day for that matter):
function closestDate($day){
$day = ucfirst($day);
if(date('l', time()) == $day)
return date("Y-m-d", time());
else if(abs(time()-strtotime('next '.$day)) < abs(time()-strtotime('last '.$day)))
return date("Y-m-d", strtotime('next '.$day));
else
return date("Y-m-d", strtotime('last '.$day));
}
Input: a day of the week ("sunday", "Monday", etc.)
Output: If I asked for the nearest "sunday" and today is:
"Sunday": I will get today's date
"Monday": I will get yesterday's date
"Saturday: I will get tomorrow's date
Hope this helps :)
As the top answer suggests, using PHP's strtotime() function is the easiest way.
However, instead of using if statements as he suggests, you could simply reset back to the previous Sunday and grab the dates you require from there.
$monday = strtotime('next monday', strtotime('previous sunday'));
$friday = strtotime('next friday', strtotime('previous sunday'));
I needed a definition of the current week per ISO 8601. I want Monday to always be defined as the Monday that started this current week.
The following solution works excellent for me:
$monday = strtotime(date('o-\WW'));
$friday = strtotime("next friday",$monday);
For $monday, this method will always return the Monday that started this calendar week. unfortunately, this method relies on PHP 5.1 to parse the o date format.
To get any day of the week, you could try:
function time_for_week_day($day_name, $ref_time=null){
$monday = strtotime(date('o-\WW',$ref_time));
if(substr(strtoupper($day_name),0,3) === "MON")
return $monday;
else
return strtotime("next $day_name",$monday);
}
Usage:
time_for_week_day('wednesday');
time_for_week_day('friday',strtotime('2014-12-25'));
I was looking for a similar thing, except I wanted any Monday, not just this week. This is what I came up with:
function getSunday(DateTime $date){
$outdate = clone($date);
$day = $date->format("w"); // get the weekday (sunday is 0)
$outdate->sub(new DateInterval("P".$day."D")); // subtracting the weekday from the date always gives Sunday
return $outdate;
}
It accepts an arbitrary date and gives the Sunday. Then you can easily add back days to get Monday through Saturday.
get the current week
$week = [];
$saturday = strtotime('saturday this week');
foreach (range(0, 6) as $day) {
$week[] = date("Y-m-d", (($day * 86400) + $saturday));
}

Categories