Skip to content

Instantly share code, notes, and snippets.

@vinicius73
Forked from emtudo/DateField.php
Created January 18, 2016 14:43
Show Gist options
  • Save vinicius73/dd0db7aa444492ebc13d to your computer and use it in GitHub Desktop.
Save vinicius73/dd0db7aa444492ebc13d to your computer and use it in GitHub Desktop.
Helper para datas Laravel
<?php
namespace App\Support\Validators\Rules;
use App\Support\Helpers\Dates as DateHelper;
class DateField
{
/**
* @param string $attribute
* @param mixed $value
* @param array $parameters
* @param \Illuminate\Validation\Validator $validator
*
* @return bool
*/
public function rule($attribute, $value, $parameters, $validator)
{
return DateHelper::isValidDate($value);
}
}
<?php
namespace App\Support\Helpers;
use Carbon\Carbon;
use DateTime;
class Dates {
/**
* @param string $date
*
* @return bool
*/
public static function isInternationalValid($date)
{
if (!(preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)) {
return false;
}
$date=explode("-", $date);
return checkdate($date[1], $date[2], $date[0]));
}
/**
* @param string $date
*
* @return bool
*/
public static function isBrazilianValid($date)
{
if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/", $date)) {
return false;
}
$date=explode("/", $date);
return checkdate($date[1], $date[0], $date[2]));
}
/**
* @param string $date
*
* @return bool
*/
public static function isValidDate($date)
{
return (bool) (static::isInternationalValid($date) or static::isBrazilianValid($date));
}
/**
* @param $value
*
* @return Carbon
*
* @throws \InvalidArgumentException
*/
public static function toCarbonObject($value)
{
if($value instanceof DateTime)
{
return Carbon::instance($value);
}
if(static::isInternationalValid($value)) {
return Carbon::createFromFormat('Y-m-d', $value);
}
if(static::isBrazilianValid($value))
{
return Carbon::createFromFormat('d/m/Y', $value);
}
throw new \InvalidArgumentException("[{$value}] not is valid date");
}
}
<?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