Get Current Date and Time
Creates the current date and time with an explicit timezone, then returns common display, ISO 8601, and Unix timestamp formats.
Purpose
Creates the current date and time with an explicit timezone, then returns common display, ISO 8601, and Unix timestamp formats.
Snippet details
ContextDate TimeLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Get Current Date and Time.
*
* Purpose:
* Creates a current timestamp with an explicit timezone and returns formats
* commonly needed by controllers, logs, and user-facing pages.
*
* @param string $timezone_name Valid PHP timezone name.
* @return array Current date/time values in multiple safe formats.
*/
function ogSnippetGetCurrentDateAndTime(string $timezone_name): array {
$timezone_name = trim($timezone_name);
if ($timezone_name === '') {
$timezone_name = 'UTC';
}
if (in_array($timezone_name, timezone_identifiers_list(), true) === false) {
$timezone_name = 'UTC';
}
$timezone = new DateTimeZone($timezone_name);
$current_time = new DateTimeImmutable('now', $timezone);
return array(
'timezone' => $timezone_name,
'display' => $current_time->format('F j, Y g:i A T'),
'iso_8601' => $current_time->format(DateTimeInterface::ATOM),
'database' => $current_time->format('Y-m-d H:i:s'),
'unix_timestamp' => $current_time->getTimestamp()
);
}
$mission_clock = ogSnippetGetCurrentDateAndTime('America/New_York');
echo 'Stargate mission clock: '.$mission_clock['display'];
echo "
";
echo 'Database value: '.$mission_clock['database'];