Date and Time and Weekend

Asked

Viewed 117 times

4

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

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

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

But when it is weekend (Saturday and Sunday), I want him to schedule with the same idea, at the same time (from the execution of the script), but that it be for Monday.

How do I do that?

  • http://www.timestampgenerator.com/ This site calculates the Stamp team

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, then just add 5 * 60 segundos, that gives 300, so PHP doesn’t need to make an unnecessary call to strtotime and a complex interpretation of strings.

Once done, just test if the result has dropped over the weekend, and add a day or two as the result:

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

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


Here we have a version with strtotime, more like your:

$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, although shorter this second version, it performs internally a much larger amount of operations far more complex than the first code, to make the textual interpretation of values. In short, it is technically inferior.

  • @Bacco I think I know this one next monday of some conversation, huh

  • Guys, unfortunately he arrow for Monday, always at 12:00

  • I need it to be just the current schedule, that the script was run.....

  • The first version respects the schedule and is technically superior, but to do it on the second, just concatenate the current time in the 'next Monday' . Actually I only posted this second, because probably someone with less knowledge would post, and could be taken as best solution by mistake. strtotime( 'next monday '.date('H:i:s', $timestamp), time() )

  • Ah, got it. But once thanks. Sensational your tips...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.