Theron Luhn
Theron Luhn

Reputation: 4092

PHP: Discover if day resides in the last week of the month

A client wants a newsletter to be automatically generated every Monday, showing the schedule for the upcoming week. That's easy:

if(date('N', $time)==1) { /* Stuff */ }

Attach that to a crontab running nightly and I'm good to go.

However, if the newsletter is being generated in the last week of the month, it needs to show the schedule for the upcoming month. How would I determine when the monthly schedule needs to be generated?

Upvotes: 2

Views: 1278

Answers (5)

Nah
Nah

Reputation: 1768

I know this a answered but this will help more:

PHP's built-in time functions make this even simple. http://php.net/manual/en/function.strtotime.php

// Get first Friday of next month.
$timestamp = strtotime('first fri of next month');

// Get second to last Friday of the current month.
$timestamp = strtotime('last fri of this month -7 days');

// Format a timestamp as a human-meaningful string.
$formattedDate = date('F j, Y', strtotime('first wed of last month'));

Upvotes: 0

Phil
Phil

Reputation: 165069

You can use the t date format param to see how many days are in the particular month. Try

if ((date('t', $time) - date('j', $time)) > 6) {
    // in the last week of the month
}

Upvotes: 0

Jeremy Roman
Jeremy Roman

Reputation: 16355

One way might be to see if next Monday is in a different month.

if (date('n', $time) != date('n', $time + 7*24*60*60)) { ... }

You could be fancier, but this seems consistent with your existing code.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191829

date('m') == date('m', strtotime('+1 week'))

If the month a week from the date the report is running is different than the current month, show the report!

Upvotes: 5

Paul
Paul

Reputation: 141935

if(date('n', $time) !== date('n', $time+518400)){
    // Six days from now it will be a new month
}

Upvotes: 0

Related Questions