Skip to content
← Back to Snippets
Code

Modify a DateTime Object

Modifies a DateTimeImmutable value with an explicit timezone and returns original and adjusted dates without mutating the original value.

Purpose

Modifies a DateTimeImmutable value with an explicit timezone and returns original and adjusted dates without mutating the original value.

Snippet details

ContextDateLevelPracticalCopy-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.
 */

/**
 * Modify a DateTime Object.
 *
 * Purpose:
 * Applies a DateTime modify expression while preserving the original date value.
 *
 * @param string $start_date Date accepted by DateTimeImmutable.
 * @param string $timezone_name Valid PHP timezone name.
 * @param string $modify_expression DateTime modify expression.
 * @return array Original and modified date strings.
 */
function ogSnippetModifyDatetimeObject(string $start_date, string $timezone_name, string $modify_expression): 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);
	$original_date = new DateTimeImmutable($start_date, $timezone);
	$modified_date = $original_date->modify($modify_expression);

	if ($modified_date === false) {
		$modified_date = $original_date;
	}

	return array(
		'timezone' => $timezone_name,
		'original' => $original_date->format('Y-m-d H:i:s T'),
		'modified' => $modified_date->format('Y-m-d H:i:s T')
	);
}

$jump_window = ogSnippetModifyDatetimeObject('2026-07-02 21:00:00', 'America/New_York', '+3 hours');

echo 'Galactica jump window: '.$jump_window['modified'];