Created
March 24, 2017 06:13
-
-
Save anjan011/7135dfbf53bc48cbe385cc9a618f453f to your computer and use it in GitHub Desktop.
Changes the format of a given date/time string
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 | |
/** | |
* 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