Skip to content

Instantly share code, notes, and snippets.

@mityukov
Created January 23, 2018 09:53
Show Gist options
  • Save mityukov/ac1fe21239f4384ccd0b0ba2f24b6055 to your computer and use it in GitHub Desktop.
Save mityukov/ac1fe21239f4384ccd0b0ba2f24b6055 to your computer and use it in GitHub Desktop.
Helpers to work with date in Laravel
<?php
function carbon($dateTime = null)
{
if (is_null($dateTime)) {
return \Carbon\Carbon::now();
}
if (is_numeric($dateTime)) { // timestamp is passed:
return \Carbon\Carbon::createFromTimestamp($dateTime);
}
if (is_object($dateTime)) { // DateTime or Carbon (probably) is passed
return \Carbon\Carbon::instance($dateTime);
}
return\Carbon\Carbon::parse($dateTime); // ok, consider it's a string to parse
}
function date_or_text($expression, $defaultText = '-', $format = 'd.m.Y')
{
if ($expression === 0 || $expression === '' || is_null($expression)) {
return $defaultText;
}
$date = carbon($expression);
return (int)$date->format('Y') > 1970 ? $date->format($format) : $defaultText;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment