Skip to content

Instantly share code, notes, and snippets.

@anjan011
Created March 24, 2017 06:13
Show Gist options
  • Save anjan011/7135dfbf53bc48cbe385cc9a618f453f to your computer and use it in GitHub Desktop.
Save anjan011/7135dfbf53bc48cbe385cc9a618f453f to your computer and use it in GitHub Desktop.
Changes the format of a given date/time string
<?php
/**
* Parses the given datetime string and changes it to the given format. This uses strtotime()
* to convert the datetime to timestamp, then changes format using date()
*
* @param string $dateStr String representing the datetime. If empty current datetime is used.
* @param string $format The desired format. Default: d/m/Y
* @param string $defaultIfInvalid A value to be returned if the given datetime is invalid
*
* @return string
*/
public static function formatDate($dateStr = '',$format = 'd/m/Y',$defaultIfInvalid = '-') {
$dateStr = trim($dateStr);
if(!$dateStr) {
$dateStr = date( 'Y-m-d H:i:s' );
}
$format = trim($format);
if(!$format) {
$format = 'd/m/Y';
}
$ts = strtotime($dateStr);
if(!$ts) {
return $defaultIfInvalid;
}
return date($format,$ts);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment