Date and Time and Weekend

4

I have a script , which does automatic scheduling of tasks.

Through the line below, I get the current date / time, add another 5 minutes, and the script gets scheduled.

$timeStamp = strtotime("+5 minutes", time());

But when it's a weekend (Saturday and Sunday), I want it to schedule with the same idea, at the same time (of the script execution), but for Monday.

How do I do this?

    
asked by anonymous 06.05.2016 / 04:14

1 answer

6

First, you can simplify your line like this:

$timeStamp = time() + 300;

This avoids a lot of internal operations and gives the same result. time returns the value in seconds, so just add 5 * 60 segundos , which gives 300 , so PHP does not need to make an unnecessary call to strtotime and a complex interpretation of strings.

Once this is done, just test if the result fell on the weekend, and add a day or two depending on the result:

$timeStamp = time() + 300;
$weekday = date( 'N', $timeStamp );
if( $weekday > 5 ) $timeStamp += ( 8 - $weekday ) * 86400;
  • $weekday = date( 'N', $timestamp) gets the day of the week, being 1 second and 7 sunday

  • If the result is greater than 5 (that is, Saturday or Sunday), add 86400 seconds (that is, a day, 24 * 60 * 60 ) multiplied by 8 - $weekday , which gives a day if it is 7 (Sunday), or two days if it is 6 Saturday, effectively playing the second schedule.


Here we have a version with strtotime , more similar to yours:

$timeStamp = strtotime( '+5 minutes', time() );
if( date( 'N', $timeStamp ) > 5 ) $timeStamp = strtotime( 'next monday', $timeStamp );

Or, keeping the time:

if( date( 'N', $timeStamp ) > 5 )
   $timeStamp = strtotime( 'next monday '.date('H:i:s', $timeStamp), time() )

But do not be fooled, even though this second version is shorter, it internally performs a much larger number of operations far more complex than the first code, to do textual interpretation of values. In short, it is technically inferior.

    
06.05.2016 / 04:51