This no good to ya - http://php.net/manual/en/function.date.php
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");
}
}
@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.
Please or to participate in this conversation.