Skip to content

Instantly share code, notes, and snippets.

@lutzissler
Last active August 15, 2021 20:17
Show Gist options
  • Save lutzissler/df8707ee25657982f3a6f2bb1d347ace to your computer and use it in GitHub Desktop.
Save lutzissler/df8707ee25657982f3a6f2bb1d347ace to your computer and use it in GitHub Desktop.
Works like strftime() but allows for multiple occurences of the formatting tokens, just like sprintf(). Also, add capability for 'O' (uppercase letter “oh”) which creates an ordinal day suffix, 'K' for the shorted 24 hour format possible ('8' instead of '08:00', '12' for '12:00', '12:15' for '12:15'), 'L' for the shortest 12 hour format possible…
function multiple_strftime($format) {
if (func_num_args() < 2) {
return $format;
}
$args = func_get_args();
return strftime(preg_replace_callback('/%(\d)\$(.)/', function ($match) use ($args) {
if (isset($args[$match[1]])) {
if ($match[2] == 'O') {
// Ordinal day suffix
return date('S', $args[$match[1]]);
} else if ($match[2] == 'K') {
// Shortest 24-hour hour and minute possible
return trim_and_filter(str_replace(':00', '', strftime('%k:%M', $args[$match[1]])));
} else if ($match[2] == 'L') {
// Shortest 12-hour hour and minute possible
return trim_and_filter(str_replace(':00', '', strftime('%l:%M', $args[$match[1]])));
} else if ($match[2] == 'N') {
// One or two digit representation of the month
return intval(strftime('%m', $args[$match[1]]));
} else if ($match[2] == 'f') {
// True single-date representation of the day
return trim(strftime('%e', $args[$match[1]]));
}
return strftime('%' . $match[2], $args[$match[1]]);
}
return $match[0];
}, preg_replace('/%([OKLN])/', '%1\\$$1', $format)), $args[1]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment