I have this function to format a date from the database into a human-friendly format, but the date is an optional field and can be null. Is there an elegant way for date be formatted if it exists or be ' ' if it is null?
public function start_date_formatted()
{
return date("M j, 'y", strtotime($this->start_date));
}
Try this code:
public function start_date_formatted()
{
if( !is_null($this->start_date) ) {
return date("M j, 'y", strtotime($this->start_date));
}
return '';
}
I think this will work
public function start_date_formatted()
{
if ($this->start_date)) {
return date("M j, 'y", strtotime($this->start_date));
} else {
return 0; // or whatever you want to return
}
}
Here is a helper to validate date:
function validateDate($date, $format = 'Y-m-d')
{
$d = DateTime::createFromFormat($format, $date);
return $d && $d->format($format) == $date;
}
Hope this will help you!!
You can uset isset, it will check if the date is set or not
public function start_date_formatted()
{
if ( isset($this->start_date) && !( is_null($this->start_date) ) ) { // Check if the properties is set and not null (maybe is_null is overkill)
return date("M j, 'y", strtotime($this->start_date));
} else {
return '';
}
}