hixbe/time

High-precision NTP time synchronization package with CLI tools

Installs: 4

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/hixbe/time

dev-main 2025-12-16 14:38 UTC

This package is auto-updated.

Last update: 2025-12-16 14:42:31 UTC


README

High-precision NTP time synchronization package with powerful CLI tools

A professional-grade PHP package for querying NTP servers and synchronizing system time with network time servers. Built with Hixbe's primary server time.hixbe.com for ultra-reliable time synchronization.

PHP Version License: MIT

Features

Rich Feature Set

  • 🚀 High-performance NTP client
  • 📊 Raw packet inspection & analysis
  • ⏱️ Precise timestamp conversion (NTP to Unix)
  • 🔄 Continuous sync mode with configurable intervals
  • 📡 Multiple server support (Hixbe, pool.ntp.org, etc.)
  • 📋 Detailed verbose reporting
  • 🎨 Beautiful CLI with multiple output formats
  • 🔐 Type-safe implementation with readonly properties
  • ⚡ Minimal dependencies (requires sockets extension)

Requirements

  • PHP 8.1 or higher
  • sockets extension enabled

Installation

composer require hixbe/time

Quick Start

CLI Usage

# Get current time from Hixbe server
./vendor/bin/hixbe-time

# Verbose mode with raw packet details
./vendor/bin/hixbe-time --verbose

# Output as JSON
./vendor/bin/hixbe-time --json

# Get time offset (useful for scripts)
./vendor/bin/hixbe-time --offset

# Continuous synchronization (every 5 seconds)
./vendor/bin/hixbe-time --continuous

# Custom interval (every 2 seconds)
./vendor/bin/hixbe-time --continuous --interval 2000

# Query different server
./vendor/bin/hixbe-time --server pool.ntp.org --verbose

# Show only the offset
./vendor/bin/hixbe-time --offset

Programmatic Usage

<?php

use Hixbe\Time\Core\NTPClient;
use Hixbe\Time\Core\NTPClientConfig;

// Basic usage
$client = new NTPClient();
$result = $client->query();
echo $result->parsed->timestamps->transmit->date->format('Y-m-d H:i:s');

// Get current time
$time = $client->getTime();
echo $time->format('Y-m-d H:i:s');

// Get offset between local and server time
$offsetMs = $client->getOffset();
echo sprintf('System is %s by %.0fms', $offsetMs > 0 ? 'slow' : 'fast', abs($offsetMs));

// Custom server
$config = new NTPClientConfig(
    host: 'time.google.com',
    timeout: 3.0
);
$customClient = new NTPClient($config);
$time = $customClient->getTime();

API Reference

NTPClient

Main class for NTP queries.

class NTPClient
{
    public function __construct(?NTPClientConfig $config = null);
    
    /**
     * Query NTP server
     * @throws Exception
     */
    public function query(): NTPQueryResult;
    
    /**
     * Get current time from NTP server
     * @throws Exception
     */
    public function getTime(): DateTime;
    
    /**
     * Get offset between local and server time
     * @return float Offset in milliseconds (positive = local is slow)
     * @throws Exception
     */
    public function getOffset(): float;
}

NTPClientConfig

Configuration options for NTP client.

class NTPClientConfig
{
    public function __construct(
        public readonly string $host = 'time.hixbe.com',
        public readonly int $port = 123,
        public readonly float $timeout = 5.0,
        public readonly array $fallbackServers = ['time.google.com', 'pool.ntp.org']
    );
}

NTPQueryResult

Result from NTP query containing all response data.

class NTPQueryResult
{
    public readonly string $buffer;              // Raw response buffer
    public readonly string $hexDump;             // Hexadecimal dump
    public readonly ParsedNTPPacket $parsed;     // Parsed packet data
    public readonly string $serverAddress;       // Server IP address
    public readonly DateTime $clientReceiveTime; // Client receive timestamp
    public readonly DateTime $clientOriginateTime; // Client send timestamp
    public readonly ?string $usedServer;         // Server hostname used
}

CLI Options

Usage: hixbe-time [OPTIONS]

High-precision NTP time synchronization

Options:
  -s, --server <server>     NTP server to query (default: time.hixbe.com)
  -j, --json                Output in JSON format
  -v, --verbose             Verbose output with packet details
  -o, --offset              Show only time offset in milliseconds
  -c, --continuous          Continuous synchronization mode
  -i, --interval <ms>       Interval for continuous mode in milliseconds (default: 5000)
  -h, --help                Show this help message
  --version                 Show version information

Examples

Get Server Time

<?php

use Hixbe\Time\Core\NTPClient;

$client = new NTPClient();
$serverTime = $client->getTime();
echo "Server time: " . $serverTime->format('Y-m-d H:i:s.v');

Check Time Synchronization

<?php

use Hixbe\Time\Core\NTPClient;

$client = new NTPClient();
$offset = $client->getOffset();

if (abs($offset) > 1000) {
    echo "⚠️  WARNING: System clock is off by {$offset}ms\n";
} else {
    echo "✅ System clock is synchronized (offset: {$offset}ms)\n";
}

Query Multiple Servers

<?php

use Hixbe\Time\Core\NTPClient;
use Hixbe\Time\Core\NTPClientConfig;

$servers = ['time.hixbe.com', 'time.google.com', 'pool.ntp.org'];

foreach ($servers as $server) {
    $config = new NTPClientConfig(host: $server);
    $client = new NTPClient($config);
    
    try {
        $result = $client->query();
        echo "{$server}: {$result->parsed->timestamps->transmit->iso}\n";
    } catch (Exception $e) {
        echo "{$server}: Error - {$e->getMessage()}\n";
    }
}

Continuous Monitoring

<?php

use Hixbe\Time\Core\NTPClient;

$client = new NTPClient();

while (true) {
    try {
        $result = $client->query();
        $serverTime = $result->parsed->timestamps->transmit->date;
        $offset = $client->getOffset();
        
        echo sprintf(
            "%s | Offset: %+.0fms\n",
            $serverTime->format('Y-m-d\TH:i:s.v\Z'),
            $offset
        );
    } catch (Exception $e) {
        echo "Error: {$e->getMessage()}\n";
    }
    
    sleep(5); // Wait 5 seconds
}

Output Formats

Default Format

======================================================================
🕐 HIXBE TIME SYNC
======================================================================

Server:        154.26.137.94 (time.hixbe.com)
UTC Time:      2025-12-16T04:27:07.341Z
Local Time:    2025-12-16 04:27:07.341 +00:00
Offset:        +0.480 seconds
Precision:     ±231 (2^x sec)
Stratum:       2
======================================================================

JSON Format

{
  "timestamp": 1765859251781,
  "iso": "2025-12-16T04:27:31.781Z",
  "server": {
    "address": "154.26.137.94",
    "stratum": 2,
    "referenceId": "0xD8EF230C"
  },
  "offset": 524,
  "precision": 231,
  "version": 4
}

Verbose Format

Shows detailed packet analysis including:

  • All timestamps (reference, originate, receive, transmit)
  • Raw NTP timestamp data in hexadecimal
  • Complete packet header information
  • Full hex dump of the response packet

Testing

# Run tests
composer test

# Run tests with coverage
composer test-coverage

License

MIT License - see LICENSE file for details.

Author

Hixbe - https://hixbe.com

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Links