S
S
Sergey Zhuzhgov2022-02-17 20:50:13
PHP
Sergey Zhuzhgov, 2022-02-17 20:50:13

How to display 00.00.0000 in PHP using the date format as text, such as "second saturday of february"?

Asked the question "PHP relative dates. How to designate, for example, the third Tuesday of the month, or the last Thursday of the month, or the first Monday of the month?" ( https://qna.habr.com/q/1116576 )
Experts helped, Thank you.

Then the following question arose - how now, by a date like 02/20/2022, display the text "second saturday of february" ???
or like this:
"last sunday of may"
"second sunday of september"
"first sunday of december"
"third friday of september"
"fourth sunday of july"

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
FanatPHP, 2022-02-17
@FanatPHP

In the work of a programmer, it is important to rely not only on the help of strangers, but also to use the knowledge gained in high school, as well as common sense.
In this case, despite the fact that the task at first glance is frighteningly difficult, it can be easily solved by a quick-witted fifth grader.
You just need to take a closer look at the date.
Which part is difficult?
How to get the day of the week?
How to get a month?
How to calculate how many whole weeks have passed until a certain date from the beginning of the month?
These are all ridiculous tasks, each of which is solved in 30 seconds
. Oh, I forgot about last. Perhaps this is the arithmetic stumbling block? ;-)

S
Slava Rozhnev, 2022-02-17
@rozhnev

https://stackoverflow.com/questions/32615861/get-w...

I
Immortal_pony, 2022-02-18
@Immortal_pony

function dateToText($date) {
    $monthOfYear = date("F Y", strtotime($date));
    $daysInMonth = date("d", strtotime("last day of {$monthOfYear}"));
    $dayOfMonth = date("d", strtotime($date));
    $dayOfWeek = date("N", strtotime($date));
    $occurance = 0;
    $maxOccurance = 0;

    foreach (range(1, $daysInMonth) as $day) {
        if (date("N", strtotime("{$day} {$monthOfYear}")) == $dayOfWeek) {
            $maxOccurance++;
            
            if ($day <= $dayOfMonth) {
                $occurance++;
            }
        }
    }
    
    $weekdayNumber = $occurance == $maxOccurance
        ? "last"
        : match($occurance) {
            1 => "first",
            2 => "second",
            3 => "third",
            4 => "fourth"
        }
    ;
    
    $text = $weekdayNumber . " " . date("l \\o\\f F", strtotime($date));
    
    return strtolower($text);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question