Primordyx Framework Documentation

TimeHelper
in package

Comprehensive time and timezone utility with formatting, comparison, and conversion capabilities

Static utility class providing extensive time manipulation, timezone conversion, duration formatting, and relative time calculation functionality. Handles microsecond-precision timestamps, ISO 8601 formatting, timezone comparisons, and human-readable time descriptions for international applications and precise time tracking.

Core Capabilities

  • ISO 8601 Formatting: Precise timestamp formatting with microsecond support
  • Timezone Operations: Conversion, comparison, and offset calculations
  • Duration Formatting: Human-readable elapsed time and duration strings
  • Relative Time: "Time ago" and "time until" descriptions
  • Localization: Local timezone formatting and system integration
  • Precision Timing: Microsecond-accurate timestamp handling

Timestamp Precision

All methods support microsecond-precision floating-point timestamps from microtime(true) and handle both integer Unix timestamps and fractional seconds for high-precision timing applications like performance monitoring and API benchmarking.

Timezone Support

Comprehensive timezone handling with:

  • Daylight Saving Time (DST) detection
  • UTC offset calculations in seconds and hours
  • Regional timezone listing and validation
  • Cross-timezone time comparison and conversion
  • Local system timezone integration

Error Handling Philosophy

Methods use graceful error handling returning null or "Invalid timestamp" strings rather than throwing exceptions, making the class safe for use in logging and display contexts where exceptions could disrupt application flow.

Integration Points

  • Timer Class: Provides timing utilities via TimeHelper::now() and elapsedDescription()
  • Token Class: ISO formatting via TimeHelper::iso() for token expiration
  • Logging Systems: Timestamp formatting for audit trails and debugging
  • API Responses: Standardized time formatting for client consumption
Tags
since
1.0.0
example

Basic Timestamp Formatting

// Current time in various formats
$now = TimeHelper::now(); // 1705334400.123456
$iso = TimeHelper::iso($now); // "2025-01-15T14:00:00.123Z"
$local = TimeHelper::toLocal($now); // "2025-01-15 9:00:00 AM"
$current = TimeHelper::nowIso(); // Current time as ISO string
example

Timezone Operations

// Compare timezones
$comparison = TimeHelper::compareTimezones('America/New_York', 'Europe/London');
$localToUTC = TimeHelper::compareLocalTo('UTC');

// Timezone information
$nycInfo = TimeHelper::describeTimezone('America/New_York');
$isDST = TimeHelper::isDst('Europe/London');
$offset = TimeHelper::utcOffsetHours('Asia/Tokyo'); // 9.0
example

Duration and Relative Time

// Duration formatting
$duration = TimeHelper::secondsToDuration(3665); // "1h 1m 5s"
$elapsed = TimeHelper::elapsedDescription($startTime, $endTime); // "1.23 sec"

// Relative time descriptions
$ago = TimeHelper::timeAgo(time() - 3600); // "1 hours ago"
$until = TimeHelper::timeUntil(time() + 1800); // "in 30 minutes"
$relative = TimeHelper::relative($timestamp); // "3 minutes ago" or "in 5 hours"
example

Advanced Usage

// Parse ISO dates
$timestamp = TimeHelper::parseIso('2025-01-15T14:30:00.000Z');

// List timezones by region
$europeanZones = TimeHelper::listTimezones('EUROPE');
$allZones = TimeHelper::listTimezones();

// Validation and utilities
$isValid = TimeHelper::isValidTimezone('America/New_York'); // true
$rounded = TimeHelper::roundToNearestSecond(1705334400.789); // 1705334401
example

Performance Monitoring Integration

class ApiTimer {
    private static $startTime;

    public static function begin() {
        self::$startTime = TimeHelper::now();
    }

    public static function end() {
        $elapsed = TimeHelper::elapsedDescription(self::$startTime);
        error_log("API call completed in: $elapsed");
        return $elapsed;
    }
}

Table of Contents

Methods

compareLocalTo()  : array<string|int, mixed>|null
Compare local system timezone to target timezone
compareLocalToJson()  : string
Get local to target timezone comparison as formatted JSON string
compareTimezones()  : array<string|int, mixed>|null
Compare two timezones and return comprehensive difference analysis
currentOffset()  : int|null
Get current UTC offset for timezone in seconds
describeTimezone()  : array<string|int, mixed>|null
Get comprehensive information about specific timezone
elapsedDescription()  : string
Format elapsed time between timestamps as human-readable duration string
formatCompare()  : string
Format timezone comparison data into human-readable display string
isDst()  : bool|null
Check if timezone is currently observing Daylight Saving Time
iso()  : string
Convert timestamp to ISO 8601 format with microsecond precision and timezone control
isValidTimezone()  : bool
Validate timezone identifier against PHP's timezone database
listTimezones()  : array<string|int, string>
Get list of timezone identifiers with optional regional filtering
localTimezone()  : string
Get system's default timezone identifier
now()  : float
Get current timestamp with microsecond precision
nowIso()  : string
Get current timestamp formatted as ISO 8601 string
parseIso()  : float|null
Parse ISO 8601 date string and convert to floating-point timestamp
printCompare()  : void
Output formatted timezone comparison directly to console
relative()  : string
Generate relative time description automatically detecting past or future
roundToNearestSecond()  : int
Round floating-point timestamp to nearest whole second
secondsToDuration()  : string
Convert seconds into human-readable duration string with appropriate units
timeAgo()  : string
Describe how long ago a timestamp occurred relative to reference point
timestamp()  : string
Alias for iso() method providing convenient timestamp formatting
timestampToLocalString()  : string
Convert timestamp to human-readable local time string with optional date inclusion
timeUntil()  : string
Describe how far into the future a timestamp is from reference point
timezoneOffset()  : int
Calculate hour difference between two timezones at specific point in time
toLocal()  : string
Alias for timestampToLocalString() providing convenient local time formatting
utcOffsetHours()  : float|null
Get timezone's current UTC offset in hours as floating-point number

Methods

compareLocalTo()

Compare local system timezone to target timezone

public static compareLocalTo(string $targetTz) : array<string|int, mixed>|null

Convenience method that compares the system's default timezone (from date_default_timezone_get()) to specified target timezone. Simplifies common use case of comparing user's local time to specific timezone.

Local Timezone Source

Uses PHP's date_default_timezone_get() to determine local timezone, which can be set via date_default_timezone_set() or php.ini configuration.

Parameters
$targetTz : string

Target timezone to compare against local

Tags
since
1.0.0
example

Local to Target Comparison

// Assuming local timezone is America/New_York
$comparison = TimeHelper::compareLocalTo('Europe/London');

if ($comparison) {
    echo "Your local time: {$comparison['from']['local_time']}\n";
    echo "London time: {$comparison['to']['local_time']}\n";
    echo "Difference: {$comparison['difference_hours']} hours\n";
}
example

User Timezone Display

function showUserTimezone($targetTimezone) {
    $comparison = TimeHelper::compareLocalTo($targetTimezone);

    if ($comparison) {
        $diff = $comparison['difference_hours'];
        $direction = $diff >= 0 ? 'ahead of' : 'behind';
        $hours = abs($diff);

        return "Your local time is $hours hours $direction $targetTimezone";
    }

    return "Unable to compare with $targetTimezone";
}

echo showUserTimezone('UTC');
// "Your local time is 5 hours behind UTC"
see
compareTimezones()

For comparing any two timezones

see
localTimezone()

For getting local timezone identifier

Return values
array<string|int, mixed>|null

Timezone comparison data, or null if target timezone invalid

compareLocalToJson()

Get local to target timezone comparison as formatted JSON string

public static compareLocalToJson(string $targetTz) : string

Combines compareLocalTo() functionality with JSON formatting for API responses, configuration files, or debugging output. Provides pretty-printed JSON for improved readability.

Parameters
$targetTz : string

Target timezone to compare against local

Tags
since
1.0.0
example

JSON Comparison Output

$json = TimeHelper::compareLocalToJson('Asia/Tokyo');
echo $json;

// Output:
// {
//     "from": {
//         "timezone": "America/New_York",
//         "local_time": "2025-01-15 09:00:00",
//         "utc_offset": -5,
//         "abbreviation": "EST"
//     },
//     "to": {
//         "timezone": "Asia/Tokyo",
//         "local_time": "2025-01-15 23:00:00",
//         "utc_offset": 9,
//         "abbreviation": "JST"
//     },
//     "difference_hours": 14
// }
example

API Response Integration

function getTimezoneComparison($targetTimezone) {
    $json = TimeHelper::compareLocalToJson($targetTimezone);

    header('Content-Type: application/json');
    echo $json;
}
see
compareLocalTo()

For array format comparison

see
formatCompare()

For human-readable string format

Return values
string

Pretty-printed JSON comparison data

compareTimezones()

Compare two timezones and return comprehensive difference analysis

public static compareTimezones(string $fromTz, string $toTz) : array<string|int, mixed>|null

Provides detailed comparison between two timezones including local times, UTC offsets, abbreviations, and hour difference. Essential for scheduling applications and cross-timezone coordination.

Returned Comparison Structure

  • from: Source timezone information (timezone, local_time, utc_offset, abbreviation)
  • to: Target timezone information (same structure as 'from')
  • difference_hours: Numeric hour difference (positive = target ahead)

Difference Calculation

  • Positive difference: Target timezone ahead of source
  • Negative difference: Target timezone behind source
  • Zero difference: Timezones currently have same offset
Parameters
$fromTz : string

Source timezone identifier

$toTz : string

Target timezone identifier

Tags
since
1.0.0
example

Timezone Comparison

$comparison = TimeHelper::compareTimezones('America/New_York', 'Asia/Tokyo');

if ($comparison) {
    echo "From: {$comparison['from']['timezone']}\n";
    echo "Local time: {$comparison['from']['local_time']} ({$comparison['from']['abbreviation']})\n";
    echo "\n";
    echo "To: {$comparison['to']['timezone']}\n";
    echo "Local time: {$comparison['to']['local_time']} ({$comparison['to']['abbreviation']})\n";
    echo "\n";
    echo "Time difference: {$comparison['difference_hours']} hours\n";
}

// Output:
// From: America/New_York
// Local time: 2025-01-15 09:00:00 (EST)
// To: Asia/Tokyo
// Local time: 2025-01-15 23:00:00 (JST)
// Time difference: 14 hours
example

Meeting Time Calculator

function findBestMeetingTime($participantTimezones, $preferredHour = 14) {
    $baseTimezone = reset($participantTimezones);
    $analysis = [];

    foreach ($participantTimezones as $participant => $timezone) {
        $comparison = TimeHelper::compareTimezones($baseTimezone, $timezone);
        if ($comparison) {
            $localHour = $preferredHour + $comparison['difference_hours'];
            $analysis[$participant] = [
                'timezone' => $timezone,
                'local_hour' => $localHour,
                'suitable' => ($localHour >= 9 && $localHour <= 17)
            ];
        }
    }

    return $analysis;
}

$participants = [
    'Alice' => 'America/New_York',
    'Bob' => 'Europe/London',
    'Charlie' => 'Asia/Singapore'
];

$analysis = findBestMeetingTime($participants, 14);
example

Travel Planning

function planTravelTimes($departureTimezone, $arrivalTimezone, $flightDuration) {
    $comparison = TimeHelper::compareTimezones($departureTimezone, $arrivalTimezone);

    if ($comparison) {
        $timeDiff = $comparison['difference_hours'];

        return [
            'departure_tz' => $departureTimezone,
            'arrival_tz' => $arrivalTimezone,
            'time_difference' => $timeDiff,
            'jet_lag_hours' => abs($timeDiff),
            'flight_duration_hours' => $flightDuration,
            'total_travel_impact' => $flightDuration + abs($timeDiff)
        ];
    }

    return null;
}
see
compareLocalTo()

For comparing local timezone to target

see
formatCompare()

For human-readable comparison formatting

see
printCompare()

For direct comparison output

Return values
array<string|int, mixed>|null

Comprehensive timezone comparison, or null if either timezone invalid

currentOffset()

Get current UTC offset for timezone in seconds

public static currentOffset(string $tz) : int|null

Calculates the current UTC offset for specified timezone, accounting for Daylight Saving Time and regional time variations. Returns offset in seconds for precise time calculations and conversions.

Offset Calculation

  • Positive values: Timezone ahead of UTC (e.g., +3600 for UTC+1)
  • Negative values: Timezone behind UTC (e.g., -18000 for UTC-5)
  • Zero: UTC timezone
  • null: Invalid timezone

DST Awareness

Automatically accounts for Daylight Saving Time when calculating offset, providing accurate offset for current date and time.

Parameters
$tz : string

Valid timezone identifier

Tags
since
1.0.0
example

Offset Calculations

// Get offsets for various timezones
$offsets = [
    'UTC' => TimeHelper::currentOffset('UTC'),                    // 0
    'EST' => TimeHelper::currentOffset('America/New_York'),       // -18000 (winter)
    'GMT' => TimeHelper::currentOffset('Europe/London'),         // 0 (winter)
    'JST' => TimeHelper::currentOffset('Asia/Tokyo'),            // 32400
];

foreach ($offsets as $zone => $offset) {
    $hours = $offset / 3600;
    echo "$zone: UTC" . ($hours >= 0 ? '+' : '') . $hours . "\n";
}
example

Time Conversion

function convertToTimezone($utcTimestamp, $targetTimezone) {
    $offset = TimeHelper::currentOffset($targetTimezone);
    if ($offset !== null) {
        return $utcTimestamp + $offset;
    }
    return $utcTimestamp; // Return original if conversion fails
}
see
utcOffsetHours()

For offset in hours

see
timezoneOffset()

For offset between two timezones

see
isDst()

For DST status detection

Return values
int|null

UTC offset in seconds, or null if timezone invalid

describeTimezone()

Get comprehensive information about specific timezone

public static describeTimezone(string $tz) : array<string|int, mixed>|null

Returns detailed timezone metadata including current local time, UTC offset, DST status, and timezone abbreviation. Provides complete timezone context for display and calculation purposes.

Returned Information Structure

  • name: Timezone identifier (e.g., 'America/New_York')
  • local_time: Current time in timezone (Y-m-d H:i:s format)
  • utc_offset: Hours offset from UTC (float, can be negative)
  • is_dst: Boolean indicating current DST status
  • abbreviation: Timezone abbreviation (e.g., 'EST', 'PST')

Error Handling

Returns null for invalid timezone identifiers rather than throwing exceptions, enabling safe use in validation and display contexts.

Parameters
$tz : string

Valid timezone identifier

Tags
since
1.0.0
example

Timezone Information Display

$zones = ['America/New_York', 'Europe/London', 'Asia/Tokyo'];

foreach ($zones as $zone) {
    $info = TimeHelper::describeTimezone($zone);
    if ($info) {
        echo "Timezone: {$info['name']}\n";
        echo "Local Time: {$info['local_time']}\n";
        echo "UTC Offset: " . ($info['utc_offset'] >= 0 ? '+' : '') . $info['utc_offset'] . "\n";
        echo "DST Active: " . ($info['is_dst'] ? 'Yes' : 'No') . "\n";
        echo "Abbreviation: {$info['abbreviation']}\n";
        echo "---\n";
    }
}
example

World Clock Implementation

class WorldClock {
    private static $watchedTimezones = [
        'New York' => 'America/New_York',
        'London' => 'Europe/London',
        'Tokyo' => 'Asia/Tokyo',
        'Sydney' => 'Australia/Sydney'
    ];

    public static function displayAll() {
        foreach (self::$watchedTimezones as $city => $timezone) {
            $info = TimeHelper::describeTimezone($timezone);
            if ($info) {
                $dst = $info['is_dst'] ? ' (DST)' : '';
                echo "$city: {$info['local_time']} {$info['abbreviation']}$dst\n";
            }
        }
    }
}

WorldClock::displayAll();
// New York: 2025-01-15 09:30:00 EST
// London: 2025-01-15 14:30:00 GMT
// Tokyo: 2025-01-15 23:30:00 JST
// Sydney: 2025-01-16 01:30:00 AEDT (DST)
example

Timezone Selection with Details

function getTimezoneOptionsWithDetails($region = null) {
    $timezones = TimeHelper::listTimezones($region);
    $options = [];

    foreach ($timezones as $tz) {
        $info = TimeHelper::describeTimezone($tz);
        if ($info) {
            $dst = $info['is_dst'] ? ' DST' : '';
            $label = "{$info['name']} (UTC{$info['utc_offset']} {$info['abbreviation']}$dst)";
            $options[$tz] = $label;
        }
    }

    return $options;
}
see
isDst()

For DST status only

see
currentOffset()

For offset only

see
compareTimezones()

For timezone comparison

Return values
array<string|int, mixed>|null

Associative array of timezone information, or null if invalid

elapsedDescription()

Format elapsed time between timestamps as human-readable duration string

public static elapsedDescription(float $start[, float|null $end = null ][, int $precision = 2 ]) : string

Calculates time difference and formats into intuitive duration descriptions with appropriate units (milliseconds, seconds, minutes, hours). Automatically selects most appropriate unit and precision for optimal readability.

Format Selection Logic

  • < 1 second: "123.45 ms" (milliseconds with precision)
  • < 1 minute: "12.34 sec" (seconds with precision)
  • < 1 hour: "5m 23.45s" (minutes and seconds)
  • ≥ 1 hour: "2h 15m" (hours and minutes only)

Precision Control

Precision parameter controls decimal places in final unit display, providing flexibility for different contexts from debugging (high precision) to user display (low precision).

Parameters
$start : float

Start timestamp (usually from microtime(true))

$end : float|null = null

End timestamp (default: current time)

$precision : int = 2

Decimal places for time display (default: 2)

Tags
since
1.0.0
example

Performance Timing

$startTime = microtime(true);

// ... perform some operation ...
usleep(1500000); // Sleep for 1.5 seconds

$endTime = microtime(true);
$duration = TimeHelper::elapsedDescription($startTime, $endTime);
echo "Operation took: $duration"; // "Operation took: 1.50 sec"

// Without end time (uses current time)
$duration2 = TimeHelper::elapsedDescription($startTime);
echo "Total elapsed: $duration2";
example

Different Precision Levels

$start = microtime(true);
usleep(123456); // ~0.123 seconds
$end = microtime(true);

$high = TimeHelper::elapsedDescription($start, $end, 6); // "123.456000 ms"
$med = TimeHelper::elapsedDescription($start, $end, 2);  // "123.46 ms"
$low = TimeHelper::elapsedDescription($start, $end, 0);  // "123 ms"
example

Timer Integration

class OperationTimer {
    private $phases = [];

    public function startPhase($name) {
        $this->phases[$name] = microtime(true);
    }

    public function endPhase($name) {
        if (isset($this->phases[$name])) {
            $duration = TimeHelper::elapsedDescription($this->phases[$name]);
            echo "Phase '$name' took: $duration\n";
        }
    }
}
see
now()

For current timestamp generation

see
secondsToDuration()

For seconds-to-duration conversion

Return values
string

Human-readable elapsed time description

formatCompare()

Format timezone comparison data into human-readable display string

public static formatCompare(array<string|int, mixed> $data) : string

Transforms timezone comparison array into formatted multi-line string with visual separators and clear information hierarchy. Ideal for console output, reports, or debugging displays.

Format Structure

  • Header with timezone names and arrow indicator
  • Separator line for visual clarity
  • From timezone: time, abbreviation, UTC offset
  • To timezone: time, abbreviation, UTC offset
  • Separator line
  • Summary with hour difference

Error Handling

Returns "Invalid comparison data." for malformed or missing comparison data.

Parameters
$data : array<string|int, mixed>

Timezone comparison data from compareTimezones()

Tags
since
1.0.0
example

Formatted Comparison Display

$comparison = TimeHelper::compareTimezones('America/New_York', 'Europe/London');
$formatted = TimeHelper::formatCompare($comparison);
echo $formatted;

// Output:
// Comparing America/New_York → Europe/London
// -------------------------------------
// From: 2025-01-15 09:00:00 (EST, UTC-5)
// To:   2025-01-15 14:00:00 (GMT, UTC+0)
// -------------------------------------
// Time difference: 5 hours
example

Report Generation

function generateTimezoneReport($timezones) {
    $report = "Timezone Comparison Report\n";
    $report .= str_repeat('=', 50) . "\n\n";

    $baseTimezone = array_shift($timezones);

    foreach ($timezones as $timezone) {
        $comparison = TimeHelper::compareTimezones($baseTimezone, $timezone);
        $report .= TimeHelper::formatCompare($comparison) . "\n\n";
    }

    return $report;
}
see
compareTimezones()

For generating comparison data

see
printCompare()

For direct output formatting

Return values
string

Formatted multi-line comparison display

isDst()

Check if timezone is currently observing Daylight Saving Time

public static isDst(string $tz) : bool|null

Determines DST status for specified timezone by examining current date and timezone rules. Essential for applications dealing with time-sensitive operations across regions with different DST observance patterns.

DST Detection Method

Uses DateTime::format('I') which returns 1 during DST periods and 0 otherwise. Checks current system time against timezone's DST rules.

Return Values

  • true: Timezone currently observing DST
  • false: Timezone not observing DST (standard time)
  • null: Invalid timezone or detection failure
Parameters
$tz : string

Valid timezone identifier (e.g., 'America/New_York')

Tags
since
1.0.0
example

DST Detection

// Check various timezones for DST
$zones = ['America/New_York', 'Europe/London', 'Asia/Tokyo', 'UTC'];

foreach ($zones as $zone) {
    $dst = TimeHelper::isDst($zone);
    $status = $dst === true ? 'DST' : ($dst === false ? 'Standard' : 'Unknown');
    echo "$zone: $status\n";
}
example

Conditional Time Display

function displayTimeWithDST($timezone) {
    $info = TimeHelper::describeTimezone($timezone);
    $dstStatus = TimeHelper::isDst($timezone) ? ' (DST)' : ' (Standard)';

    return $info['local_time'] . $dstStatus;
}

echo displayTimeWithDST('America/New_York'); // "2025-01-15 14:30:00 (Standard)"
see
currentOffset()

For current UTC offset calculation

see
describeTimezone()

For comprehensive timezone information

Return values
bool|null

DST status or null if timezone invalid

iso()

Convert timestamp to ISO 8601 format with microsecond precision and timezone control

public static iso(float $ts[, bool $utc = true ]) : string

Formats floating-point timestamps into standardized ISO 8601 strings with optional UTC or local timezone representation. Handles microsecond precision and provides consistent international timestamp formatting for APIs, logging, and data exchange.

ISO 8601 Format Features

  • Microsecond precision: Preserves fractional seconds up to microseconds
  • Timezone flexibility: UTC (Z suffix) or local timezone (+/-offset)
  • Standards compliance: Full ISO 8601 specification adherence
  • Error handling: Returns "Invalid timestamp" for malformed input

Output Format Examples

  • UTC: "2025-01-15T14:30:00.123Z"
  • Local: "2025-01-15T09:30:00.123-05:00"
  • Error: "Invalid timestamp"

Precision Handling

Extracts microseconds from floating-point timestamps and incorporates them into the formatted string using DateTimeImmutable modification for accuracy.

Parameters
$ts : float

Unix timestamp with microsecond precision (e.g., microtime(true))

$utc : bool = true

Whether to format in UTC (true) or local timezone (false)

Tags
since
1.0.0
example

Timestamp Formatting Scenarios

$now = microtime(true); // 1705334400.123456

// UTC formatting (default)
$utc = TimeHelper::iso($now, true);  // "2025-01-15T14:00:00.123Z"
$utc = TimeHelper::iso($now);        // Same as above (UTC default)

// Local timezone formatting
$local = TimeHelper::iso($now, false); // "2025-01-15T09:00:00.123-05:00"

// Error handling
$invalid = TimeHelper::iso(-1);        // "Invalid timestamp"
$invalid = TimeHelper::iso(INF);       // "Invalid timestamp"
example

API Response Integration

function formatApiResponse($data, $timestamp) {
    return [
        'data' => $data,
        'timestamp' => TimeHelper::iso($timestamp, true),
        'server_time' => TimeHelper::iso(microtime(true), false)
    ];
}
see
timestamp()

For alias to this method

see
nowIso()

For current time ISO formatting

see
timestampToLocalString()

For human-readable local formatting

Return values
string

ISO 8601 formatted timestamp or "Invalid timestamp" on error

isValidTimezone()

Validate timezone identifier against PHP's timezone database

public static isValidTimezone(string $tz) : bool

Checks if provided string is valid timezone identifier recognized by PHP's DateTimeZone class. Essential for user input validation and configuration verification before timezone operations.

Validation Method

Uses DateTimeZone::listIdentifiers() to get authoritative list of valid timezone identifiers and performs exact string matching.

Parameters
$tz : string

Timezone identifier to validate

Tags
since
1.0.0
example

Timezone Validation

$timezones = [
    'America/New_York',    // Valid
    'Europe/London',       // Valid
    'Invalid/Timezone',    // Invalid
    'UTC',                 // Valid
    'GMT',                 // Valid
    'America/Invalid'      // Invalid
];

foreach ($timezones as $tz) {
    $valid = TimeHelper::isValidTimezone($tz) ? 'Valid' : 'Invalid';
    echo "$tz: $valid\n";
}
example

User Input Validation

function validateUserTimezone($userInput) {
    if (empty($userInput)) {
        return ['valid' => false, 'error' => 'Timezone cannot be empty'];
    }

    if (TimeHelper::isValidTimezone($userInput)) {
        return ['valid' => true, 'timezone' => $userInput];
    }

    return ['valid' => false, 'error' => 'Invalid timezone identifier'];
}

$result = validateUserTimezone($_POST['timezone'] ?? '');
if ($result['valid']) {
    // Proceed with valid timezone
    $info = TimeHelper::describeTimezone($result['timezone']);
} else {
    echo "Error: " . $result['error'];
}
example

Configuration Validation

class AppConfig {
    public static function setTimezone($timezone) {
        if (TimeHelper::isValidTimezone($timezone)) {
            date_default_timezone_set($timezone);
            return true;
        }

        throw new InvalidArgumentException("Invalid timezone: $timezone");
    }
}
see
listTimezones()

For getting list of valid timezones

see
describeTimezone()

For timezone information

Return values
bool

True if timezone is valid, false otherwise

listTimezones()

Get list of timezone identifiers with optional regional filtering

public static listTimezones([string|null $region = null ]) : array<string|int, string>

Returns array of valid timezone identifiers from PHP's timezone database, with optional filtering by geographic region. Essential for timezone selection interfaces and validation systems.

Regional Filtering Options

  • 'AFRICA': African timezones (Africa/Cairo, etc.)
  • 'AMERICA': American timezones (America/New_York, etc.)
  • 'ASIA': Asian timezones (Asia/Tokyo, etc.)
  • 'EUROPE': European timezones (Europe/London, etc.)
  • 'AUSTRALIA': Australian timezones
  • 'PACIFIC': Pacific region timezones
  • 'UTC': UTC and related timezones
  • null or 'ALL': All available timezones

Case Insensitivity

Region parameter is case-insensitive ('europe', 'EUROPE', 'Europe' all work).

Parameters
$region : string|null = null

Optional region filter (case-insensitive)

Tags
since
1.0.0
example

Regional Timezone Listing

// Get all European timezones
$europeanZones = TimeHelper::listTimezones('EUROPE');
echo "European timezones: " . count($europeanZones) . "\n";
foreach (array_slice($europeanZones, 0, 5) as $zone) {
    echo "- $zone\n";
}
// Output includes: Europe/London, Europe/Paris, Europe/Berlin, etc.

// Get all timezones
$allZones = TimeHelper::listTimezones();
echo "Total timezones: " . count($allZones) . "\n";
example

Timezone Selection Interface

function buildTimezoneSelectOptions($region = null) {
    $timezones = TimeHelper::listTimezones($region);
    $options = [];

    foreach ($timezones as $timezone) {
        $info = TimeHelper::describeTimezone($timezone);
        $label = $timezone . ' (UTC' .
                ($info['utc_offset'] >= 0 ? '+' : '') .
                $info['utc_offset'] . ')';
        $options[$timezone] = $label;
    }

    return $options;
}

// Build dropdown for American timezones
$americanOptions = buildTimezoneSelectOptions('AMERICA');
example

Timezone Validation

function validateTimezone($timezone, $allowedRegion = null) {
    $validTimezones = TimeHelper::listTimezones($allowedRegion);
    return in_array($timezone, $validTimezones, true);
}

// Validate user-provided timezone
$userTimezone = $_POST['timezone'] ?? '';
if (validateTimezone($userTimezone)) {
    echo "Valid timezone: $userTimezone";
} else {
    echo "Invalid timezone provided";
}
see
isValidTimezone()

For single timezone validation

see
describeTimezone()

For timezone information

Return values
array<string|int, string>

Array of timezone identifier strings

localTimezone()

Get system's default timezone identifier

public static localTimezone() : string

Returns the currently configured default timezone for the PHP system. Wrapper around date_default_timezone_get() providing consistent interface for accessing system timezone configuration.

Timezone Source

Returns timezone set by:

  1. date_default_timezone_set() function calls
  2. date.timezone php.ini directive
  3. System timezone detection (if available)
  4. UTC fallback (if no timezone configured)
Tags
since
1.0.0
example

System Timezone Display

$systemTz = TimeHelper::localTimezone();
echo "System timezone: $systemTz\n";

// Display current local time
$localTime = TimeHelper::toLocal(TimeHelper::now());
echo "Local time: $localTime ($systemTz)\n";
example

Application Configuration

function initializeApplication() {
    $configTz = Config::get('app.timezone', 'UTC');
    $currentTz = TimeHelper::localTimezone();

    if ($currentTz !== $configTz) {
        echo "Setting timezone from $currentTz to $configTz\n";
        date_default_timezone_set($configTz);
    }
}
example

User Timezone Comparison

function compareWithUserTimezone($userTimezone) {
    $systemTz = TimeHelper::localTimezone();
    return TimeHelper::compareTimezones($systemTz, $userTimezone);
}
see
compareLocalTo()

For comparing local timezone to others

see
describeTimezone()

For local timezone details

Return values
string

Current system default timezone identifier

now()

Get current timestamp with microsecond precision

public static now() : float

Returns current Unix timestamp as floating-point number including microseconds for high-precision timing operations. Wrapper around microtime(true) providing consistent interface for current time access throughout TimeHelper methods.

Precision Details

  • Integer part: Unix timestamp in seconds since epoch
  • Fractional part: Microseconds (6 decimal places)
  • Example: 1705334400.123456 represents precise moment in time

Use Cases

  • Performance timing and benchmarking
  • High-precision timestamp generation
  • Timer implementations
  • Duration calculations requiring microsecond accuracy
Tags
since
1.0.0
example

High-Precision Timing

$start = TimeHelper::now();

// Perform some operation
for ($i = 0; $i < 1000; $i++) {
    hash('sha256', "test$i");
}

$end = TimeHelper::now();
$duration = $end - $start;

echo "Operation took: " . number_format($duration * 1000, 2) . " ms\n";
example

Timestamp Comparison

$timestamp1 = TimeHelper::now();
usleep(100000); // Sleep 0.1 seconds
$timestamp2 = TimeHelper::now();

$difference = $timestamp2 - $timestamp1;
echo "Time difference: " . number_format($difference, 6) . " seconds\n";
// Output: "Time difference: 0.100123 seconds"
example

Timer Class Integration

class SimpleTimer {
    private $startTime;

    public function start() {
        $this->startTime = TimeHelper::now();
    }

    public function elapsed() {
        return TimeHelper::now() - $this->startTime;
    }

    public function stop() {
        $elapsed = $this->elapsed();
        echo "Timer: " . TimeHelper::elapsedDescription($this->startTime) . "\n";
        return $elapsed;
    }
}
see
elapsedDescription()

For formatting elapsed time

see
iso()

For formatting timestamps

Return values
float

Current Unix timestamp with microsecond precision

nowIso()

Get current timestamp formatted as ISO 8601 string

public static nowIso([bool $utc = true ]) : string

Convenience method that combines current time retrieval with ISO formatting, providing immediate access to properly formatted current timestamps for logging, API responses, and data recording.

Current Time Sources

Uses microtime(true) internally to capture current time with microsecond precision, then formats using iso() method for consistent output.

Parameters
$utc : bool = true

Whether to format in UTC (true) or local timezone (false)

Tags
throws
Exception

If timestamp formatting operations fail

since
1.0.0
example

Current Time Formatting

// Current time in UTC
$utcNow = TimeHelper::nowIso();        // "2025-01-15T14:30:00.123Z"
$utcNow = TimeHelper::nowIso(true);    // Same as above

// Current time in local timezone
$localNow = TimeHelper::nowIso(false); // "2025-01-15T09:30:00.123-05:00"
example

Logging Integration

function logEvent($message, $level = 'INFO') {
    $timestamp = TimeHelper::nowIso();
    error_log("[$timestamp] [$level] $message");
}

logEvent('User logged in successfully');
// Logs: [2025-01-15T14:30:00.123Z] [INFO] User logged in successfully
see
iso()

For timestamp formatting with custom timestamps

see
now()

For current timestamp as float

Return values
string

Current time as ISO 8601 formatted string

parseIso()

Parse ISO 8601 date string and convert to floating-point timestamp

public static parseIso(string $iso) : float|null

Converts ISO 8601 formatted date strings back into Unix timestamps with microsecond precision. Handles various ISO 8601 formats including timezone indicators and provides robust parsing for API data and stored timestamps.

Supported ISO Formats

  • Basic: "2025-01-15T14:30:00"
  • With timezone: "2025-01-15T14:30:00Z"
  • With offset: "2025-01-15T14:30:00+05:00"
  • With microseconds: "2025-01-15T14:30:00.123456Z"

Error Handling

Returns null for invalid date strings rather than throwing exceptions, making it safe for use in validation and data processing contexts.

Parameters
$iso : string

ISO 8601 formatted date string

Tags
since
1.0.0
example

ISO String Parsing

// Various ISO format parsing
$timestamps = [
    TimeHelper::parseIso('2025-01-15T14:30:00Z'),        // UTC
    TimeHelper::parseIso('2025-01-15T09:30:00-05:00'),   // EST offset
    TimeHelper::parseIso('2025-01-15T14:30:00.123Z'),    // With microseconds
    TimeHelper::parseIso('invalid-date'),                 // null (error)
];

foreach ($timestamps as $ts) {
    echo $ts !== null ? date('Y-m-d H:i:s', $ts) : 'Invalid';
    echo "\n";
}
example

API Data Processing

function processApiTimestamp($isoString) {
    $timestamp = TimeHelper::parseIso($isoString);

    if ($timestamp !== null) {
        return [
            'unix_timestamp' => $timestamp,
            'local_display' => TimeHelper::toLocal($timestamp),
            'relative' => TimeHelper::relative($timestamp)
        ];
    }

    return ['error' => 'Invalid timestamp format'];
}

$result = processApiTimestamp('2025-01-15T14:30:00Z');
example

Validation and Conversion

class DateValidator {
    public static function validateAndConvert($dateString) {
        $timestamp = TimeHelper::parseIso($dateString);

        if ($timestamp === null) {
            throw new InvalidArgumentException('Invalid ISO date format');
        }

        return $timestamp;
    }
}
see
iso()

For formatting timestamps to ISO strings

see
nowIso()

For current time as ISO string

Return values
float|null

Unix timestamp with microseconds, or null if parsing fails

printCompare()

Output formatted timezone comparison directly to console

public static printCompare(string $fromTz, string $toTz) : void

Convenience method that combines compareTimezones() and formatCompare() to provide immediate formatted output for debugging and console applications. Eliminates need for intermediate variables in simple display scenarios.

Parameters
$fromTz : string

Source timezone identifier

$toTz : string

Target timezone identifier

Tags
since
1.0.0
example

Direct Console Output

// Direct output for debugging
TimeHelper::printCompare('America/Los_Angeles', 'Asia/Tokyo');

// Output:
// Comparing America/Los_Angeles → Asia/Tokyo
// -------------------------------------
// From: 2025-01-15 06:00:00 (PST, UTC-8)
// To:   2025-01-15 23:00:00 (JST, UTC+9)
// -------------------------------------
// Time difference: 17 hours
example

Quick Timezone Debugging

// Quick debugging in console applications
echo "Meeting timezone analysis:\n";
TimeHelper::printCompare('America/New_York', 'Europe/Berlin');
echo "\n";
TimeHelper::printCompare('Europe/Berlin', 'Asia/Singapore');
see
compareTimezones()

For getting comparison data

see
formatCompare()

For formatting without direct output

Return values
void

Outputs formatted comparison directly via echo

relative()

Generate relative time description automatically detecting past or future

public static relative(float $ts[, float|null $reference = null ]) : string

Intelligent relative time formatter that automatically determines whether timestamp is in past or future and applies appropriate description format. Combines timeAgo() and timeUntil() functionality with "now" detection for comprehensive relative time handling.

Automatic Direction Detection

  • Past timestamps: Uses timeAgo() format ("X ago")
  • Future timestamps: Uses timeUntil() format ("in X")
  • Current time: Returns "now" for timestamps within 0.5 seconds

Precision Threshold

Timestamps within 0.5 seconds of reference point are considered "now" to handle minor timing variations and provide stable user experience.

Parameters
$ts : float

Timestamp to describe (past, present, or future)

$reference : float|null = null

Reference point (default: current time)

Tags
since
1.0.0
example

Automatic Relative Time

$now = time();

// Automatic detection
echo TimeHelper::relative($now - 3600); // "1 hours ago"
echo TimeHelper::relative($now + 1800); // "in 30 minutes"
echo TimeHelper::relative($now);        // "now"
echo TimeHelper::relative($now + 0.3);  // "now" (within threshold)
example

Universal Timeline Display

function formatTimelineEvent($eventTimestamp) {
    return TimeHelper::relative($eventTimestamp);
}

$events = [
    ['name' => 'Meeting', 'time' => time() + 3600],
    ['name' => 'Launch', 'time' => time() - 1800],
    ['name' => 'Current', 'time' => time()],
];

foreach ($events as $event) {
    $when = formatTimelineEvent($event['time']);
    echo "{$event['name']}: $when\n";
}
// Output:
// Meeting: in 1 hours
// Launch: 30 minutes ago
// Current: now
example

Smart Activity Feed

class ActivityFeed {
    public static function formatActivity($activity) {
        $timeDesc = TimeHelper::relative($activity->timestamp);
        return "{$activity->user} {$activity->action} $timeDesc";
    }
}

// Usage
echo ActivityFeed::formatActivity($activity);
// "john posted a comment 5 minutes ago"
// "jane scheduled a meeting in 2 hours"
see
timeAgo()

For past-only descriptions

see
timeUntil()

For future-only descriptions

Return values
string

Automatic relative time description

roundToNearestSecond()

Round floating-point timestamp to nearest whole second

public static roundToNearestSecond(float $ts) : int

Converts microsecond-precision timestamps to integer seconds using standard rounding rules. Useful for reducing precision when exact microsecond timing is not required or for compatibility with systems expecting integer timestamps.

Rounding Behavior

  • 0.4 seconds: Rounds down to 0
  • 0.5 seconds: Rounds up to 1
  • 0.6 seconds: Rounds up to 1
  • Uses PHP's round() function for consistent behavior
Parameters
$ts : float

Floating-point timestamp with microseconds

Tags
since
1.0.0
example

Timestamp Rounding

$precise = microtime(true); // 1705334400.789
$rounded = TimeHelper::roundToNearestSecond($precise); // 1705334401

// Multiple timestamps
$timestamps = [1705334400.2, 1705334400.5, 1705334400.8];
foreach ($timestamps as $ts) {
    echo TimeHelper::roundToNearestSecond($ts) . "\n";
}
// Output: 1705334400, 1705334401, 1705334401
example

Database Storage

function storeEvent($eventData) {
    $eventData['timestamp'] = TimeHelper::roundToNearestSecond(microtime(true));
    Database::insert('events', $eventData);
}
Return values
int

Integer timestamp rounded to nearest second

secondsToDuration()

Convert seconds into human-readable duration string with appropriate units

public static secondsToDuration(float|int $seconds) : string

Transforms numeric seconds into intuitive duration descriptions using hours, minutes, and seconds notation. Automatically selects relevant units and ensures at least one unit is always displayed for clarity.

Duration Format Logic

  • Hours: Included if ≥ 3600 seconds (1 hour)
  • Minutes: Included if ≥ 60 seconds (1 minute)
  • Seconds: Always included unless zero and other units present
  • Zero duration: Shows "0s" rather than empty string

Output Examples

  • 3665 seconds: "1h 1m 5s"
  • 125 seconds: "2m 5s"
  • 45 seconds: "45s"
  • 0 seconds: "0s"
Parameters
$seconds : float|int

Duration in seconds (fractional seconds truncated)

Tags
since
1.0.0
example

Duration Formatting

// Various duration lengths
echo TimeHelper::secondsToDuration(3665);  // "1h 1m 5s"
echo TimeHelper::secondsToDuration(125);   // "2m 5s"
echo TimeHelper::secondsToDuration(45);    // "45s"
echo TimeHelper::secondsToDuration(0);     // "0s"
echo TimeHelper::secondsToDuration(7200);  // "2h"
echo TimeHelper::secondsToDuration(3600);  // "1h"
example

Process Timing Display

function displayProcessTime($startTime) {
    $elapsed = time() - $startTime;
    $duration = TimeHelper::secondsToDuration($elapsed);
    echo "Process running for: $duration\n";
}

$processStart = time() - 3725; // Started ~1 hour ago
displayProcessTime($processStart); // "Process running for: 1h 2m 5s"
example

Video Duration Formatting

class VideoMetadata {
    public static function formatDuration($durationSeconds) {
        return TimeHelper::secondsToDuration($durationSeconds);
    }
}

$videos = [
    ['title' => 'Tutorial', 'duration' => 1845],
    ['title' => 'Quick Tip', 'duration' => 90],
];

foreach ($videos as $video) {
    $duration = VideoMetadata::formatDuration($video['duration']);
    echo "{$video['title']}: $duration\n";
}
// Output:
// Tutorial: 30m 45s
// Quick Tip: 1m 30s
see
elapsedDescription()

For elapsed time formatting with precision

Return values
string

Human-readable duration string

timeAgo()

Describe how long ago a timestamp occurred relative to reference point

public static timeAgo(float $ts[, float|null $reference = null ]) : string

Generates human-readable "time ago" descriptions for past timestamps relative to current time or specified reference point. Automatically selects appropriate time unit for optimal readability and user understanding.

Time Unit Selection

  • < 1 second: "just now"
  • < 1 minute: "X seconds ago"
  • < 1 hour: "X minutes ago"
  • < 1 day: "X hours ago"
  • ≥ 1 day: "X days ago"

Reference Point Flexibility

Allows custom reference timestamp for "ago" calculations, enabling relative time descriptions from any point in time rather than just current moment.

Parameters
$ts : float

Timestamp to describe (must be in the past)

$reference : float|null = null

Reference point (default: current time)

Tags
since
1.0.0
example

Past Time Descriptions

$now = time();

// Various past timestamps
echo TimeHelper::timeAgo($now - 30);    // "30 seconds ago"
echo TimeHelper::timeAgo($now - 300);   // "5 minutes ago"
echo TimeHelper::timeAgo($now - 3600);  // "1 hours ago"
echo TimeHelper::timeAgo($now - 86400); // "1 days ago"
echo TimeHelper::timeAgo($now - 1);     // "just now"
example

Custom Reference Point

$eventTime = strtotime('2025-01-15 12:00:00');
$referenceTime = strtotime('2025-01-15 14:30:00');

$description = TimeHelper::timeAgo($eventTime, $referenceTime);
echo $description; // "2 hours ago" (from reference point)
example

Social Media Timeline

function formatPostTime($postTimestamp) {
    return TimeHelper::timeAgo($postTimestamp);
}

foreach ($posts as $post) {
    echo $post->content . " - " . formatPostTime($post->created_at) . "\n";
}
see
timeUntil()

For future time descriptions

see
relative()

For automatic past/future detection

Return values
string

Human-readable "time ago" description

timestamp()

Alias for iso() method providing convenient timestamp formatting

public static timestamp(float $ts[, bool $utc = true ]) : string

Convenience method that delegates to iso() for consistent ISO 8601 timestamp formatting. Maintains same functionality and parameters as iso() while providing more intuitive method naming for timestamp formatting operations.

Parameters
$ts : float

Unix timestamp with microsecond precision

$utc : bool = true

Whether to format in UTC (true) or local timezone (false)

Tags
throws
Exception

If underlying iso() operations fail

since
1.0.0
example

Alias Usage

$now = microtime(true);

// These are equivalent
$iso1 = TimeHelper::iso($now, true);
$iso2 = TimeHelper::timestamp($now, true);
// Both return: "2025-01-15T14:30:00.123Z"
see
iso()

For complete method documentation and examples

Return values
string

ISO 8601 formatted timestamp or "Invalid timestamp" on error

timestampToLocalString()

Convert timestamp to human-readable local time string with optional date inclusion

public static timestampToLocalString(float $ts[, bool $includeDate = true ]) : string

Formats timestamps into user-friendly local time representations using 12-hour format with AM/PM indicators. Provides flexible date inclusion for different display contexts and maintains microsecond precision in calculations.

Output Formats

  • With date: "2025-01-15 9:30:00 AM"
  • Time only: "9:30:00 AM"
  • Error: "Invalid timestamp"

Localization Features

  • Uses system default timezone via date_default_timezone_get()
  • 12-hour format with AM/PM for user familiarity
  • Microsecond precision preserved during conversion
  • Graceful error handling for invalid timestamps

Use Cases

  • User interface time display
  • Log file human-readable timestamps
  • Dashboard and report time formatting
  • Email and notification timestamps
Parameters
$ts : float

Unix timestamp with microsecond precision

$includeDate : bool = true

Whether to include date portion (default: true)

Tags
throws
Exception

If DateTimeImmutable operations fail

since
1.0.0
example

Local Time Display Scenarios

$timestamp = microtime(true);

// Full date and time display
$full = TimeHelper::timestampToLocalString($timestamp);
echo $full; // "2025-01-15 9:30:00 AM"

// Time-only display for same-day events
$timeOnly = TimeHelper::timestampToLocalString($timestamp, false);
echo $timeOnly; // "9:30:00 AM"

// Error handling
$invalid = TimeHelper::timestampToLocalString(-1); // "Invalid timestamp"
example

User Interface Integration

function formatEventTime($eventTimestamp, $isToday = false) {
    return TimeHelper::timestampToLocalString($eventTimestamp, !$isToday);
}

// Usage in templates
$eventTime = formatEventTime($event->timestamp, $event->isToday());
echo "Event starts at: $eventTime";
see
toLocal()

For alias to this method

see
iso()

For ISO 8601 formatting

see
elapsedDescription()

For duration formatting

Return values
string

Human-readable local time string or "Invalid timestamp" on error

timeUntil()

Describe how far into the future a timestamp is from reference point

public static timeUntil(float $ts[, float|null $reference = null ]) : string

Generates human-readable "time until" descriptions for future timestamps relative to current time or specified reference point. Complements timeAgo() for comprehensive relative time description capabilities.

Time Unit Selection

  • < 1 second: "any moment now"
  • < 1 minute: "in X seconds"
  • < 1 hour: "in X minutes"
  • < 1 day: "in X hours"
  • ≥ 1 day: "in X days"

Future Time Applications

Ideal for countdowns, scheduled events, expiration times, and deadline notifications where users need intuitive future time understanding.

Parameters
$ts : float

Future timestamp to describe

$reference : float|null = null

Reference point (default: current time)

Tags
since
1.0.0
example

Future Time Descriptions

$now = time();

// Various future timestamps
echo TimeHelper::timeUntil($now + 1);     // "any moment now"
echo TimeHelper::timeUntil($now + 30);    // "in 30 seconds"
echo TimeHelper::timeUntil($now + 300);   // "in 5 minutes"
echo TimeHelper::timeUntil($now + 3600);  // "in 1 hours"
echo TimeHelper::timeUntil($now + 86400); // "in 1 days"
example

Event Countdown

function getEventCountdown($eventTimestamp) {
    if ($eventTimestamp > time()) {
        return "Event starts " . TimeHelper::timeUntil($eventTimestamp);
    } else {
        return "Event started " . TimeHelper::timeAgo($eventTimestamp);
    }
}

$eventTime = strtotime('+2 hours');
echo getEventCountdown($eventTime); // "Event starts in 2 hours"
example

Token Expiration Display

class TokenManager {
    public static function getExpirationDescription($token) {
        $expiry = $token->getExpirationTime();

        if ($expiry > time()) {
            return "Token expires " . TimeHelper::timeUntil($expiry);
        } else {
            return "Token expired " . TimeHelper::timeAgo($expiry);
        }
    }
}
see
timeAgo()

For past time descriptions

see
relative()

For automatic past/future detection

Return values
string

Human-readable "time until" description

timezoneOffset()

Calculate hour difference between two timezones at specific point in time

public static timezoneOffset(string $fromTz, string $toTz[, DateTimeInterface|null $at = null ]) : int

Computes timezone offset difference in hours, accounting for Daylight Saving Time rules at the specified date and time. Essential for accurate cross-timezone calculations and scheduling applications.

Offset Calculation

  • Positive result: Target timezone ahead of source timezone
  • Negative result: Target timezone behind source timezone
  • Zero result: Timezones have same offset
  • DST awareness: Automatically accounts for DST rules

Temporal Accuracy

Uses specific DateTime for calculation, ensuring accurate results even when DST transition dates differ between timezones or when calculating historical or future offsets.

Parameters
$fromTz : string

Source timezone identifier

$toTz : string

Target timezone identifier

$at : DateTimeInterface|null = null

Specific date/time for calculation (default: now)

Tags
throws
Exception

If timezone identifiers are invalid

since
1.0.0
example

Timezone Offset Calculations

// Current time offset calculations
$offset1 = TimeHelper::timezoneOffset('UTC', 'America/New_York');
echo "NYC is UTC$offset1\n"; // "NYC is UTC-5" (winter) or "UTC-4" (summer)

$offset2 = TimeHelper::timezoneOffset('Europe/London', 'Asia/Tokyo');
echo "Tokyo is $offset2 hours ahead of London\n";
example

Historical Offset Calculation

// Calculate offset for specific historical date
$historicalDate = new DateTime('2024-07-15'); // Summer date
$winterOffset = TimeHelper::timezoneOffset('UTC', 'Europe/London');
$summerOffset = TimeHelper::timezoneOffset('UTC', 'Europe/London', $historicalDate);

echo "London winter offset: UTC$winterOffset\n"; // UTC+0
echo "London summer offset: UTC$summerOffset\n"; // UTC+1 (BST)
example

Meeting Scheduler

function scheduleMeeting($meetingTimeUTC, $participantTimezones) {
    $schedule = [];

    foreach ($participantTimezones as $name => $timezone) {
        $offset = TimeHelper::timezoneOffset('UTC', $timezone);
        $localTime = $meetingTimeUTC + ($offset * 3600);
        $schedule[$name] = date('Y-m-d H:i:s', $localTime) . " ($timezone)";
    }

    return $schedule;
}

$utcMeeting = strtotime('2025-01-15 14:00:00 UTC');
$participants = [
    'Alice' => 'America/New_York',
    'Bob' => 'Europe/London',
    'Charlie' => 'Asia/Tokyo'
];

$schedule = scheduleMeeting($utcMeeting, $participants);
see
currentOffset()

For single timezone UTC offset

see
compareTimezones()

For comprehensive timezone comparison

Return values
int

Hour difference between timezones

toLocal()

Alias for timestampToLocalString() providing convenient local time formatting

public static toLocal(float $ts[, bool $withDate = true ]) : string

Convenience method that delegates to timestampToLocalString() for human-readable local time display. Maintains same functionality while providing intuitive method naming for local time conversion operations.

Parameters
$ts : float

Unix timestamp with microsecond precision

$withDate : bool = true

Whether to include date portion (default: true)

Tags
throws
Exception

If underlying timestampToLocalString() operations fail

since
1.0.0
example

Alias Usage

$timestamp = microtime(true);

// These are equivalent
$local1 = TimeHelper::timestampToLocalString($timestamp, true);
$local2 = TimeHelper::toLocal($timestamp, true);
// Both return: "2025-01-15 9:30:00 AM"
see
timestampToLocalString()

For complete method documentation and examples

Return values
string

Human-readable local time string or "Invalid timestamp" on error

utcOffsetHours()

Get timezone's current UTC offset in hours as floating-point number

public static utcOffsetHours(string $tz) : float|null

Converts timezone's UTC offset from seconds to hours for more intuitive display and calculation. Handles fractional hour offsets and DST transitions automatically.

Offset Representation

  • Positive values: Timezone ahead of UTC (e.g., 9.0 for UTC+9)
  • Negative values: Timezone behind UTC (e.g., -5.0 for UTC-5)
  • Fractional values: Timezones with 30/45 minute offsets (e.g., 5.5 for UTC+5:30)
  • null: Invalid timezone identifier
Parameters
$tz : string

Valid timezone identifier

Tags
since
1.0.0
example

Hour Offset Display

$timezones = [
    'UTC',
    'America/New_York',
    'Asia/Tokyo',
    'Asia/Kolkata',      // UTC+5:30
    'Australia/Adelaide'  // UTC+9:30 (with DST variations)
];

foreach ($timezones as $tz) {
    $offset = TimeHelper::utcOffsetHours($tz);
    if ($offset !== null) {
        $sign = $offset >= 0 ? '+' : '';
        echo "$tz: UTC$sign$offset\n";
    }
}

// Output:
// UTC: UTC+0
// America/New_York: UTC-5 (winter) or UTC-4 (summer)
// Asia/Tokyo: UTC+9
// Asia/Kolkata: UTC+5.5
// Australia/Adelaide: UTC+9.5 or UTC+10.5 (DST)
example

Offset-Based Time Calculation

function convertUtcToTimezone($utcTimestamp, $targetTimezone) {
    $offsetHours = TimeHelper::utcOffsetHours($targetTimezone);
    if ($offsetHours !== null) {
        return $utcTimestamp + ($offsetHours * 3600);
    }
    return $utcTimestamp; // Return unchanged if conversion fails
}

$utcTime = time();
$tokyoTime = convertUtcToTimezone($utcTime, 'Asia/Tokyo');
example

Display Formatting

function formatTimezoneOffset($timezone) {
    $offset = TimeHelper::utcOffsetHours($timezone);

    if ($offset === null) {
        return 'Invalid timezone';
    }

    if ($offset == 0) {
        return 'UTC';
    }

    $sign = $offset > 0 ? '+' : '';
    $hours = floor(abs($offset));
    $minutes = (abs($offset) - $hours) * 60;

    if ($minutes == 0) {
        return "UTC$sign" . ($offset > 0 ? $hours : -$hours);
    } else {
        return "UTC$sign" . ($offset > 0 ? $hours : -$hours) . ':' . sprintf('%02d', $minutes);
    }
}

echo formatTimezoneOffset('Asia/Kolkata'); // "UTC+5:30"
see
currentOffset()

For offset in seconds

see
timezoneOffset()

For difference between two timezones

see
describeTimezone()

For comprehensive timezone information

Return values
float|null

UTC offset in hours, or null if timezone invalid


        
On this page

Search results