date_timezone_set / date_timezone_get

date_timezone_set(DateTime $object, DateTimeZone $timezone): DateTime · date_timezone_get(DateTime $object): DateTimeZone

Zone-object read/write: date_timezone_set switches a DateTime instance's zone (the instant never moves; only the representation view changes) and date_timezone_get reads it back; contrast with date_default_timezone_set's process-wide default — object-level settings never pollute the global.

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

/* C has no zone database; libc exposes it through POSIX: TZ + tzset() switches the
   global zone (like PHP's date_default_timezone_set), conversions go through localtime */
int main(void) {
    struct tm utc_tm;
    memset(&utc_tm, 0, sizeof utc_tm);
    utc_tm.tm_year = 2024 - 1900;
    utc_tm.tm_mon = 0;
    utc_tm.tm_mday = 15;
    utc_tm.tm_hour = 12;
    time_t t = timegm(&utc_tm); /* POSIX: interpret the fields as UTC */

    puts("UTC");
    setenv("TZ", "UTC", 1);
    tzset();
    struct tm u = *localtime(&t);
    printf("%02d:%02d\n", u.tm_hour, u.tm_min);

    puts("Asia/Shanghai");
    setenv("TZ", "Asia/Shanghai", 1); /* IANA id resolved via the system tzdata */
    tzset();
    struct tm s = *localtime(&t);
    printf("%02d:%02d\n", s.tm_hour, s.tm_min);
    printf("%ld\n", (long)s.tm_gmtoff); /* BSD/glibc extension: offset seconds */
    return 0;
}
Output
UTC
12:00
Asia/Shanghai
20:00
28800

C++ C++26

C++26
#include <iostream>

// std has no timezone database on clang's libc++ (C++20 chrono tzdb ships in GCC's
// libstdc++; real projects use date/tz) - honest demo: a fixed-offset zone attached per value
struct Zone {
    const char *name;
    long offset_secs;
};

int main() {
    Zone utc{"UTC", 0};
    Zone sh{"Asia/Shanghai", 28800}; // +08:00, no DST
    std::cout << utc.name << "\n";
    long unix_secs = 1705320000; // 2024-01-15 12:00:00 UTC
    long wall = unix_secs + sh.offset_secs; // same instant, wall clock follows the zone
    std::cout << sh.name << "\n";
    std::cout << wall % 86400 / 3600 << ":" << (wall % 3600 / 60 < 10 ? "0" : "") << wall % 3600 / 60 << "\n";
    std::cout << sh.offset_secs << "\n";
    return 0;
}
Output
UTC
Asia/Shanghai
20:00
28800

C# v11.0.100

v11.0.100
using System;
using System.Globalization;

// object-level zone: TimeZoneInfo objects are passed around explicitly (no global switch)
Console.WriteLine(TimeZoneInfo.Utc.Id);
var dtUtc = new DateTime(2024, 1, 15, 12, 0, 0, DateTimeKind.Utc);
var sh = TimeZoneInfo.FindSystemTimeZoneById("Asia/Shanghai");
var local = TimeZoneInfo.ConvertTimeFromUtc(dtUtc, sh); // same instant, wall clock follows the zone
Console.WriteLine(sh.Id);
Console.WriteLine(local.ToString("HH:mm", CultureInfo.InvariantCulture));
Console.WriteLine(sh.GetUtcOffset(dtUtc).TotalSeconds);
Output
UTC
Asia/Shanghai
20:00
28800

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"time"
)

// object-level zone lives on the time.Time value (zone attached per value)
func main() {
	locUTC, _ := time.LoadLocation("UTC")
	dt := time.Date(2024, 1, 15, 12, 0, 0, 0, locUTC)
	fmt.Println(dt.Location())
	sh, _ := time.LoadLocation("Asia/Shanghai")
	inSh := dt.In(sh) // same instant, new zone
	fmt.Println(inSh.Location())
	fmt.Println(inSh.Format("15:04"))
	_, offset := inSh.Zone()
	fmt.Println(offset)
}
Output
UTC
Asia/Shanghai
20:00
28800

Java v27.0.1

v27.0.1
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        // object-level zone lives on the ZonedDateTime instance
        ZonedDateTime dt = ZonedDateTime.of(2024, 1, 15, 12, 0, 0, 0, ZoneId.of("UTC"));
        System.out.println(dt.getZone());
        ZonedDateTime inSh = dt.withZoneSameInstant(ZoneId.of("Asia/Shanghai")); // same instant, new zone
        System.out.println(inSh.getZone());
        System.out.println(inSh.toLocalTime());
        System.out.println(inSh.getOffset().getTotalSeconds());
    }
}
Output
UTC
Asia/Shanghai
20:00
28800

JavaScript v26.13.1

v26.13.1
// object-level zone: an options object carried per call (Intl.IANA zones)
const fmt = (tz) => new Intl.DateTimeFormat("en-GB", { timeZone: tz, hour: "2-digit", minute: "2-digit", hour12: false });
const dt = new Date(Date.UTC(2024, 0, 15, 12, 0));
console.log(fmt("UTC").format(dt));
const sh = fmt("Asia/Shanghai");
console.log(sh.resolvedOptions().timeZone);
console.log(sh.format(dt)); // 20:00: wall clock follows the zone
const parts = new Intl.DateTimeFormat("en-US", { timeZone: "Asia/Shanghai", timeZoneName: "longOffset" }).formatToParts(dt);
console.log(parts.find((p) => p.type === "timeZoneName").value); // GMT+08:00
Output
12:00
Asia/Shanghai
20:00
GMT+08:00

PHP v8.6.0

v8.6.0
// object-level timezone lives on the DateTime instance - the process default stays untouched
date_default_timezone_set("UTC"); // known baseline (global API: see date_default_timezone_set)
$dt = new DateTime("2024-01-15 12:00:00");
echo date_timezone_get($dt)->getName(), "\n"; // inherited from the global default at construction
date_timezone_set($dt, new DateTimeZone("Asia/Shanghai"));
echo date_timezone_get($dt)->getName(), "\n"; // per-object zone: swaps the view, not the instant
echo $dt->format("H:i"), "\n"; // 20:00: wall clock follows the zone (+8 from UTC)
echo $dt->getTimezone()->getOffset($dt), "\n"; // 28800 = +08:00 at that instant
echo "global still: ", date_default_timezone_get(), "\n"; // the object call never touched it
Output
UTC
Asia/Shanghai
20:00
28800
global still: UTC

Python v3.15.2

v3.15.2
from datetime import datetime
from zoneinfo import ZoneInfo

# object-level zone lives on the datetime instance - PHP's per-object semantics 1:1
dt = datetime(2024, 1, 15, 12, 0, 0, tzinfo=ZoneInfo("UTC"))
print(dt.tzinfo.key)
sh = dt.astimezone(ZoneInfo("Asia/Shanghai"))  # same instant, new zone attached
print(sh.tzinfo.key)
print(sh.strftime("%H:%M"))
print(int(sh.utcoffset().total_seconds()))
print(datetime.now().tzinfo)  # None: naive default - zones are opt-in per value
Output
UTC
Asia/Shanghai
20:00
28800
None

Rust v1.99.1

v1.99.1
// std has no timezone database (chrono + chrono-tz crates in real projects) -
// honest demo: a fixed-offset zone attached per value, the PHP semantics in miniature
#[derive(Debug)]
struct Zone {
    name: &'static str,
    offset_secs: i64,
}

fn main() {
    let utc = Zone { name: "UTC", offset_secs: 0 };
    let sh = Zone { name: "Asia/Shanghai", offset_secs: 28800 }; // +08:00, no DST
    println!("{}", utc.name);
    let unix_secs: i64 = 1_705_320_000; // 2024-01-15 12:00:00 UTC
    let wall = unix_secs + sh.offset_secs; // same instant, wall clock follows the zone
    println!("{}", sh.name);
    println!("{:02}:{:02}", wall % 86400 / 3600, wall % 3600 / 60);
    println!("{}", sh.offset_secs);
}
Output
UTC
Asia/Shanghai
20:00
28800

TypeScript v26.13.1

v26.13.1
// object-level zone: an options object carried per call (Intl.IANA zones)
const fmt = (tz: string): Intl.DateTimeFormat =>
    new Intl.DateTimeFormat("en-GB", { timeZone: tz, hour: "2-digit", minute: "2-digit", hour12: false });
const dt: Date = new Date(Date.UTC(2024, 0, 15, 12, 0));
console.log(fmt("UTC").format(dt));
const sh: Intl.DateTimeFormat = fmt("Asia/Shanghai");
console.log(sh.resolvedOptions().timeZone);
console.log(sh.format(dt)); // 20:00: wall clock follows the zone
const parts: Intl.DateTimeFormatPart[] = new Intl.DateTimeFormat("en-US", {
    timeZone: "Asia/Shanghai",
    timeZoneName: "longOffset",
}).formatToParts(dt);
console.log(parts.find((p: Intl.DateTimeFormatPart) => p.type === "timeZoneName")!.value); // GMT+08:00
Output
12:00
Asia/Shanghai
20:00
GMT+08:00

Language differences

Object-level vs global: date_timezone_set/get only touch the DateTime instance's own zone (switching zones never changes the instant, only the representation view), while date_default_timezone_set mutates the process-wide default (global mutable state, see the existing entry) — this entry's deterministic assertions: after setting, the zone name reads back "Asia/Shanghai" and the offset 28800 (Asia/Shanghai has no DST, always +08:00).

PHP: date_timezone_set($dt, new DateTimeZone($tz)) is the procedural alias of DateTime::setTimezone() (since 5.2); date_timezone_get($dt) aliases DateTime::getTimezone(); getOffset($dt) returns the zone's offset at that instant.

Python: zoneinfo.ZoneInfo (PEP 615, 3.9+) attaches to the tzinfo field; astimezone switches the zone without moving the instant; there is no global default to switch (datetimes can be naive) — datetime.now().tzinfo is simply None.

Go: time.LoadLocation reads the system tzdata; t.In(loc) switches the zone without moving the instant; Location()/Zone() read back the zone name and offset.

Java: ZoneId.of + withZoneSameInstant (zone switch, instant intact); contrast withZoneSameLocal (wall-clock-preserving zone switch — a classic trap).

C#: TimeZoneInfo.FindSystemTimeZoneById (accepts IANA ids since .NET 6) + ConvertTimeFromUtc; TimeZoneInfo objects are passed explicitly — no global switch surface.

JavaScript/TypeScript: no zone objects; the Intl.DateTimeFormat timeZone option is carried per call; formatToParts with timeZoneName: "longOffset" reads the offset back (GMT+08:00).

C/C++: libc has no object-level zones — POSIX TZ + tzset() is process-global (equivalent to date_default_timezone_set, not this entry's object level); C++20 std::chrono::locate_zone/zoned_time is the standard tzdb, but clang's libc++ does not ship it enabled (verified on this toolchain), while GCC's libstdc++ does; the example follows the honest strategy (a fixed-offset struct demonstrating the semantics) — use date/tz or chrono-tz in real projects.

Rust: std has no timezone library; real projects use chrono + chrono-tz (IANA data compiled into the binary); the example is likewise a fixed-offset honest demo.

timegm (C) and tm_gmtoff/tm_zone (BSD/glibc extensions) are platform-dependent: the validator's compile command carries -D_GNU_SOURCE and both macOS/Linux libcs provide them.