1. <?php
  2. /**
  3. * Pretty-prints timestamps with human-readable format.
  4. *
  5. * @param int|string $timestamp The timestamp to format. Can be a Unix timestamp (int) or a date string.
  6. * @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'.
  7. * @return string The formatted date and time string. Returns an empty string on error.
  8. */
  9. function prettyPrintTimestamp($timestamp, $format = 'Y-m-d H:i:s'): string
  10. {
  11. if (is_numeric($timestamp)) {
  12. // If it's a Unix timestamp
  13. $datetime = new DateTime("@$timestamp");
  14. } elseif (is_string($timestamp)) {
  15. // If it's a date string, try to parse it
  16. $datetime = new DateTime($timestamp);
  17. } else {
  18. //Invalid input
  19. return "";
  20. }
  21. return $datetime->format($format);
  22. }
  23. //Example usage
  24. echo prettyPrintTimestamp(time(), 'Y-m-d H:i:s') . "\n"; // Current timestamp, default format
  25. echo prettyPrintTimestamp(1678886400, 'F j, Y') . "\n"; // Specific timestamp, custom format
  26. echo prettyPrintTimestamp("2024-03-15 10:30:00", 'l, F j, Y') . "\n"; //Date string
  27. echo prettyPrintTimestamp("invalid date", 'Y-m-d') . "\n"; //Invalid Date
  28. ?>

Add your comment