Question

I have this probably very simple question for you all. Since I'm still learning php for me this is slightly more complicated so please take it easy.

Right, I'm trying to calculate the next date based on the current date and time. What I mean is lets say I'm working on Every Thurday and Saturday. I need to calculate when are my next working day.

I'm able to retrieve current week but can't figure out how could I set each Thursday and Sunday as my working days.

$date = date("Y-m-d",strtotime('monday this week')).' - '.date("Y-m-d",strtotime("sunday this week"));

I want the output to be something like this:

Current week 2014-05-12 To 2014-05-17

Next working day: 2014-05-14

Last working day this week: 2014-05-17

Was it helpful?

Solution

The new object oriented packages in PHP are your friend. Use DateTime: http://www.php.net/manual/en/class.datetime.php

<?php
$workDays = array("Thursday", "Saturday");
$d = new DateTime; //creates a datetime object, by default, the current time
while(!in_array($d->format("l"), $workDays)) $d->add(new DateInterval('P1D'));
print "Next work day: " . $d->format("Y-m-d");

OTHER TIPS

Try using date('w') in an if statement to give you a numeric representation of the current weekday, where Sunday == 0.

if (date('w') < 4) { // Currently Sun-Weds
   $next_wd_str = 'thursday this week';
   $last_wd_string = 'saturday last week';
} elseif (date('w') > 4 && date('w') < 6) { //Currently Fri
   $next_wd_str = 'saturday this week';
   $last_wd_string = 'thursday this week'
} elseif (date('w') ==4) { 
   $next_wd_str = 'today';
   $last_wd_string = 'saturday last week';
} else {
   $next_wd_str = 'today';
   $last_wd_string = 'thursday this week';
printf ('Next working day: ', date('Y-m-d', strtotime($next_wd_str));
printf ('Last working day: ', date('Y-m-d', strtotime($last_wd_str));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top