<?php
/**
* Pretty-prints timestamps with human-readable format.
*
* @param int|string $timestamp The timestamp to format. Can be a Unix timestamp (int) or a date string.
* @param string $format The desired date format (e.g., 'Y-m-d H:i:s', 'F j, Y'). Defaults to 'Y-m-d H:i:s'.
* @return string The formatted date and time string. Returns an empty string on error.
*/
function prettyPrintTimestamp($timestamp, $format = 'Y-m-d H:i:s'): string
{
if (is_numeric($timestamp)) {
// If it's a Unix timestamp
$datetime = new DateTime("@$timestamp");
} elseif (is_string($timestamp)) {
// If it's a date string, try to parse it
$datetime = new DateTime($timestamp);
} else {
//Invalid input
return "";
}
return $datetime->format($format);
}
//Example usage
echo prettyPrintTimestamp(time(), 'Y-m-d H:i:s') . "\n"; // Current timestamp, default format
echo prettyPrintTimestamp(1678886400, 'F j, Y') . "\n"; // Specific timestamp, custom format
echo prettyPrintTimestamp("2024-03-15 10:30:00", 'l, F j, Y') . "\n"; //Date string
echo prettyPrintTimestamp("invalid date", 'Y-m-d') . "\n"; //Invalid Date
?>
Add your comment