Get the date of the first Tuesday of each month

Asked

Viewed 124 times

3

To return the previous Tuesday I do this way:

$dia = new DateTime();
$dia->modify( 'previous tuesday' );
$terca = $dia->format('Y-m-d');

Now intended to return the first Tuesday of each month

  • Why do you keep using date($dia->format('Y-m-d'))?

2 answers

7


For you to catch the next Tuesday starting each month utilize this tuesday, example:

$dia = new DateTime();
$dia->modify( 'this tuesday' );
echo $terca = $dia->format('Y-m-d');

And to catch the First Tuesday of the current month do:

$dia = new DateTime();
$dia->modify( 'first tuesday of F Y' );
echo $terca = $dia->format('Y-m-d');

I believe the expected option is the second.

Reference: Relative formats - Datetime/date_create()

6

As I commented on Does not return date in input it makes no sense to do:

$terca = date($dia->format('Y-m-d'));

You create an object DateTime, formats in a string to use again in date? I reinforce what I said about not writing random code without understanding what you’re doing. If you don’t understand, stop and look for it. Will you use a function? Read the documentation, know the parameters, know what will be the return and, mainly, know what it does, in fact. Only then will you know if it’s really what you need at that moment.

You can return the first Tuesday of a month with:

function get_first_tuesday($year, $month) {
    return new DateTime("first tuesday of {$year}-{$month}");
}

echo get_first_tuesday('2019', '02')->format('Y-m-d'), PHP_EOL;  // 2019-02-05

And pick up every first Tuesday of every month of a year with:

function get_first_tuesdays_of_year($year) {
    for ($i = 1; $i <= 12; $i++) {
        yield get_first_tuesday($year, $i);
    }
}

$tuesdays = get_first_tuesdays_of_year(2019);

foreach ($tuesdays as $tuesday) {
    echo $tuesday->format('Y-m-d'), PHP_EOL;
}

The result would be:

2019-01-01
2019-02-05
2019-03-05
2019-04-02
2019-05-07
2019-06-04
2019-07-02
2019-08-06
2019-09-03
2019-10-01
2019-11-05
2019-12-03

In fact, you don’t even need the class DateTime here. I could do:

function get_first_tuesday($year, $month, $format = 'Y-m-d') {
    return date($format, strtotime("first tuesday of {$year}-{$month}"));
}

That would also work.

  • you’re absolutely right, it was a lack of attention to the comment you put in the other question, it really doesn’t make sense

Browser other questions tagged

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