Skip to content

Instantly share code, notes, and snippets.

@massiws
Last active March 26, 2017 01:48
Show Gist options
  • Save massiws/f32041311e88162ca04a6676b0cc2abc to your computer and use it in GitHub Desktop.
Save massiws/f32041311e88162ca04a6676b0cc2abc to your computer and use it in GitHub Desktop.
Drupal 7: date format conversion
<?php
/**
* Date conversion class.
*/
class DateFormat {
/**
* Date format conversion.
*
* Convert a date from any string format (accordingly with PHP standard) or
* from Drupal array date format to the specified format (default: Y-m-d)
*
* @param string|array $in_date
* Date to be formatted, can be different values:
* - a string in any PHP standard format
* - an array 'Drupal style': ['year' => 2015, 'month' => 11, 'day' => 25]
* - 'now' to get current date.
* @param string $format
* Any PHP supported Date and Time Formats (ex: 'timestamp', 'today', etc.)
* (see http://php.net/manual/en/datetime.formats.php).
* @param string $default
* Returning value if some errors occurs during conversion:
* - 'now': return the current date
* - (default is an empty value).
*
* @return string
* The formatted date; if there is an error during conversion,
* an empty value is returned
*/
public static function convert($in_date, $format = 'Y-m-d', $default = '') {
if (empty($in_date) || is_null($in_date)) {
return '';
}
elseif (is_string($in_date)) {
$date_time = new DateTime($in_date);
}
elseif (is_array($in_date)) {
$date_time = new DateTime(implode('-', $in_date));
}
if ($date_time == FALSE) {
// Conversion error.
switch ($default) {
case 'now':
$date_time = new DateTime();
break;
default:
return '';
}
}
if (strtolower($format) == 'timestamp') {
$out_date = $date_time->getTimestamp();
}
else {
$out_date = $date_time->format($format);
}
return $out_date;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment