Forked from vinicius73/CustomValidatorsServiceProvider.php
Created
January 18, 2016 13:36
-
-
Save dlimars/ac7ae6faebefce488091 to your computer and use it in GitHub Desktop.
Helper para datas Laravel
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support\Helpers; | |
use Carbon\Carbon; | |
use DateTime; | |
class Dates { | |
/** | |
* @param string $date | |
* | |
* @return bool | |
*/ | |
public static function isInternationalFormat($date) | |
{ | |
return (bool) (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)); | |
} | |
/** | |
* @param string $date | |
* | |
* @return bool | |
*/ | |
public static function isBrazilianFormat($date) | |
{ | |
return (bool) (preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $date)); | |
} | |
/** | |
* @param string $date | |
* | |
* @return bool | |
*/ | |
public static function isValidFormat($date) | |
{ | |
return (bool) (static::isInternationalFormat($date) or static::isBrazilianFormat($date)); | |
} | |
/** | |
* @param $value | |
* | |
* @return Carbon | |
* | |
* @throws \InvalidArgumentException | |
*/ | |
public static function toCarbonObject($value) | |
{ | |
if($value instanceof DateTime) | |
{ | |
return Carbon::instance($value); | |
} | |
if(static::isInternationalFormat($value)) { | |
return Carbon::createFromFormat('Y-m-d', $value); | |
} | |
if(static::isBrazilianFormat($value)) | |
{ | |
return Carbon::createFromFormat('d/m/Y', $value); | |
} | |
throw new \InvalidArgumentException("[{$value}] not is valid date"); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Support\Traits\Eloquent; | |
use App\Support\Helpers\Dates as DateHelper; | |
trait HasDateFieldsTrait | |
{ | |
/** | |
* @param \DateTime|\Carbon\Carbon|string $value | |
* | |
* @return \Carbon\Carbon|null | |
*/ | |
protected function valueToCarbonObject($value) | |
{ | |
if(empty($value)) { | |
return null; | |
} | |
return DateHelper::toCarbonObject($value); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment