Skip to content

Instantly share code, notes, and snippets.

@brachycera
Last active May 27, 2020 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brachycera/0a77bbb936671f1eb166 to your computer and use it in GitHub Desktop.
Save brachycera/0a77bbb936671f1eb166 to your computer and use it in GitHub Desktop.
Format mySql timestamp/date field values into many different variations
<?php
/**
* Convert a mySql timestamp / date value to a nice looking date
*
* @param string $date - mySql Database timestamp / date field value
* @param num/bol $layout - Date Layout values 1 to 7 for different styles:
* [1] eg. 01.Jan.1970, 00:10:01
* [2] eg. 01.01.1970
* [3] eg. 00:10
* [4] eg. 01 January 1970
* [5] eg. Thursday, 01. Jan. 1970
* [6] eg. January 1970
* [7] ISO-8601 week number eg. 01-1970
* [default] eg. 01.Jan.1970, 00:10
* @param string $local - set localization; default is german
* @return string
*/
public function niceDate($date, $layout = false, $local = 'de_DE') {
if ($date == '0000-00-00 00:00:00') {
return;
}
setlocale(LC_ALL, $local);
$unixTimestamp = strtotime($date);
if ($unixTimestamp <= '-1') {
$unixTimestamp = strtotime(
sprintf(
'%02s-%02s-%02s %02s:%02s:%02s',
substr($date, 0, 4),
substr($date, 4, 2),
substr($date, 6, 2),
substr($date, 8, 2),
substr($date, 10 ,2),
substr($date, 12 ,2)
)
);
}
switch ($layout) {
// eg. 01.Jan.1970, 00:10:01
case $layout == 1:
return strftime('%d.%b.%Y, %H:%M:%S', $unixTimestamp);
// eg. 01.01.1970
case $layout == 2:
return strftime('%d.%m.%Y', $unixTimestamp);
// eg. 00:10
case $layout == 3:
return strftime('%H:%M', $unixTimestamp);
// eg. 01 January 1970
case $layout == 4:
return strftime('%d %B %Y', $unixTimestamp);
// eg. Thursday, 01. Jan. 1970
case $layout == 5:
return strftime('%A, %d. %b %Y', $unixTimestamp);
// eg. January 1970
case $layout == 6:
return strftime('%B %Y', $unixTimestamp);
// ISO-8601 week number eg. 01-1970
case $layout == 7:
return strftime('%V-%Y', $unixTimestamp);
// eg. 01.Jan.1970, 00:10
default:
return strftime('%d.%b.%Y, %H:%M', $unixTimestamp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment