Skip to content

Instantly share code, notes, and snippets.

@marcosfreitas
Last active June 2, 2017 18:49
Show Gist options
  • Save marcosfreitas/6e88fb474d702ad3726cd6f75203533c to your computer and use it in GitHub Desktop.
Save marcosfreitas/6e88fb474d702ad3726cd6f75203533c to your computer and use it in GitHub Desktop.
Abstraction to get date e anyone formats
<?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