Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mstnorris's avatar

Help with formatting date string

I have an Event model with a start and end date (stored as timestamps).

What is the best way to produce a string describing the date of the event depending on a few factors, I have the beginnings of an if statement below, although I can see straight away that this will get out of hand.

The question relates to how best compare the dates and produce all possible outcomes.

    public function getDateTimeString()
    {
        $start = $this->started_at; // started_at is a timestamp on this Event model
        $end = $this->ended_at; // ended_at is a timestamp on this Event model
        
        if ( $start->isSameDay($end) ) {
            //    $dt->isYesterday(); - Produce something like "Yesterday between 09:00 and 10:00
            //    $dt->isToday(); "Earlier today from 09:00 - 10:00" or "Later today between 16:00 - 17:00" or "Started 30 minutes ago and ends at 17:00"
            //    $dt->isTomorrow(); ""Tomorrow from 09:00 until 10:00"
            //    $dt->isFuture(); "Fri 25 Mar 2016 from 09:00 - 10:00"
            //    $dt->isPast(); "Mon 21 Mar 2016 from 09:00 - 10:00"
            return "On " . $start->format("D d M Y") . " from " . $start->format("H:i") . " until " . $end->format("H:i");
        } else {
            // Same as above, but change the strings to use correct language
            return "From " . $start->format("H:i") . " on " . $start->format("D d M Y") . " until " . $end->format("H:i") . " on " . $end->format("D d M Y");
        }
    }
0 likes
7 replies
mstnorris's avatar

Nah that's not what I'm on about Lee, but thanks though. I know how to format the date into the right format, and I could just continue as I am (as shown above) but the question is about how to compare the dates in the most efficient way (which may be what I'm already doing or a switch statement).

Does that make sense? If not, I'll re-word the question.

theUnforgiven's avatar

Sorry yeah I think I understand. So what's wrong with what you have currently does it work and show what you need it to, I don't see anything wrong with that.

mstnorris's avatar

It's just messy in the controller, I haven't fleshed it out but I can see that I will have nested ifs everywhere and just wondered if there is a better solution.

goatshark's avatar
Level 14

@mstnorris: If you're mostly bugged by eye sores in the controller, you could pull it back to a class and just use the class in the controller. And, if you're going to need to deal with dates like this on multiple models, you might consider creating/using a trait and then just use MyFancyDateThingTrait on those models.

1 like
mstnorris's avatar

It's just in this model, I think I will put it into a separate class. Thanks.

Please or to participate in this conversation.