Convert Date to UNIX Timestamp
Parses a date string in an explicit timezone and returns its UNIX timestamp.
Purpose
Parses a date string in an explicit timezone and returns its UNIX timestamp.
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.
*/
/**
* Convert Date to UNIX Timestamp.
*
* Purpose:
* Converts a date/time string into a UNIX timestamp.
*
* @param string $date_text Date/time text.
* @param string $timezone_name PHP timezone name.
* @return array Timestamp conversion result.
*/
function ogSnippetConvertDateToUnixTimestamp(string $date_text, string $timezone_name): array {
$timezone_name = trim($timezone_name);
$result = array(
'ok' => false,
'timestamp' => 0,
'message' => 'Date could not be parsed.'
);
if (in_array($timezone_name, timezone_identifiers_list(), true) === false) {
$timezone_name = 'UTC';
}
try {
$timezone = new DateTimeZone($timezone_name);
$date = new DateTimeImmutable($date_text, $timezone);
$result['ok'] = true;
$result['timestamp'] = $date->getTimestamp();
$result['message'] = 'Date converted.';
} catch (Exception $exception) {
$result['message'] = 'Date could not be parsed.';
}
return $result;
}
$timestamp_report = ogSnippetConvertDateToUnixTimestamp('2026-07-02 21:00:00', 'America/New_York');
echo 'Stargate timestamp: '.$timestamp_report['timestamp'];