Last active
June 2, 2017 18:49
-
-
Save marcosfreitas/6e88fb474d702ad3726cd6f75203533c to your computer and use it in GitHub Desktop.
Abstraction to get date e anyone formats
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 | |
/** | |
* Check if a string is a valid based on $formats['input'], then format an output based on $formats['output'] | |
* @author Marcos Freitas | |
* @param string $value The string of the date | |
* @param array $formats The given input and wanted output formats of the date. | |
* @return string|boolean | |
*/ | |
public static function getDate($value, $formats){ | |
if (!isset($formats['input']) || empty($formats['input'])) { | |
$formats['input'] = 'd-m-Y'; | |
} | |
if (!isset($formats['output']) || empty($formats['output'])) { | |
$formats['output'] = 'Y-m-d'; | |
} | |
$d = \DateTime::createFromFormat($formats['input'], $value); | |
$date_errors = date_get_last_errors(); | |
if ($date_errors['error_count'] || $date_errors['warning_count']) { | |
return false; | |
} | |
if ($d && $d->format($formats['input']) === $value) { | |
return $d->format($formats['output']); | |
} else { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment