Skip to content

Date and Time

Precious Lyson edited this page Nov 13, 2026 · 2 revisions

DateTimeHandler is a lightweight, chainable wrapper around PHP's built-in DateTime class. It provides:

  • Fluent interface – chain multiple operations together
  • Explicit timezone handling – every instance is timezone-aware
  • Type-safe exception handling – converts native Throwable into DateTimeException
  • Convenience helpers – add/subtract days, hours, and minutes without manually crafting DateInterval strings
  • Timestamp interoperability – static factory for reconstructing from Unix timestamps

The class lives in the namespace:

Mlangeni\Machinjiri\Core\Date

Quick Start (Beginner)

use Mlangeni\Machinjiri\Core\Date\DateTimeHandler;

// 1. Create an instance for "now" in UTC
$now = new DateTimeHandler();

// 2. Format it
echo $now->format('Y-m-d H:i:s');   // e.g. "2024-06-01 14:30:00"

// 3. Add 3 days
$now->addDays(3);

echo $now->format('Y-m-d');         // "2024-06-04"

// 4. Chain operations
$future = (new DateTimeHandler('2024-01-01', 'Africa/Johannesburg'))
    ->addDays(10)
    ->addHours(5)
    ->format('Y-m-d H:i:s');

echo $future; // "2024-01-11 05:00:00"

That's it — you already know 80% of what you need.


Core Concepts

1. Immutability (Careful!)

DateTimeHandler is mutable, mirroring PHP's native DateTime. Methods like modify(), addDays(), setTime() change the same instance and return $this to enable chaining.

If you need a copy, clone the object manually:

$original = new DateTimeHandler('2024-01-01');
$copy     = clone $original;
$copy->addDays(5);       // $original is untouched

💡 If you rely heavily on immutable-style code, wrap calls in a helper that always clones first.

2. Timezones Are First-Class

Every handler is created with an explicit timezone (default UTC). The timezone is used at construction and preserved through all mutations.

3. Exceptions

All construction errors are normalized into a DateTimeException:

try {
    new DateTimeHandler('not a real date', 'Mars/Olympus');
} catch (\Mlangeni\Machinjiri\Core\Exceptions\DateTimeException $e) {
    echo $e->getMessage();
}

API Reference

Constructor

public function __construct(string $dateString = 'now', string $timezone = 'UTC')
Parameter Type Default Description
$dateString string 'now' Any string parseable by DateTime
$timezone string 'UTC' A valid PHP timezone identifier (e.g., 'Europe/London')

Throws: DateTimeException on invalid input.

new DateTimeHandler();                              // now, UTC
new DateTimeHandler('tomorrow', 'Asia/Tokyo');
new DateTimeHandler('2024-12-25 08:00:00', 'America/New_York');

Formatting

public function format(string $format): string

Returns a formatted string using PHP's date formatting syntax.

$handler->format('Y-m-d');           // "2024-06-01"
$handler->format('D, d M Y H:i:s');  // "Sat, 01 Jun 2024 14:30:00"
$handler->format('U');               // Unix timestamp

Modifying Dates

public function modify(string $modifier): self

Accepts any string valid for DateTime::modify(). Returns $this.

$handler->modify('+1 week');
$handler->modify('last day of this month');
$handler->modify('next Monday');

Intervals

public function addInterval(DateInterval $interval): self
public function subInterval(DateInterval $interval): self

Add or subtract a native DateInterval.

$interval = new DateInterval('P1Y2M3D');
$handler->addInterval($interval);
$handler->subInterval(new DateInterval('PT45M'));

Difference Between Two Dates

public function diff(DateTimeHandler $other): DateInterval

Returns a DateInterval representing the difference. Because it uses PHP's DateTime::diff(), the result is signed relative to $this.

$a = new DateTimeHandler('2024-01-01');
$b = new DateTimeHandler('2024-03-01');

$diff = $a->diff($b);
echo $diff->days;     // 60 (total days)
echo $diff->m;        // 2 (months)
echo $diff->invert;   // 0 if $b > $a, 1 if $b < $a

Setting Date / Time

public function setTime(int $hour, int $minute, int $second = 0): self
public function setDate(int $year, int $month, int $day): self
$handler->setTime(9, 30);        // 09:30:00
$handler->setDate(2025, 1, 1);   // January 1, 2025

Getters

public function getDateTime(): DateTime
public function getTimestamp(): int
  • getDateTime() returns the underlying DateTime object (useful for interoperability).
  • getTimestamp() returns the Unix timestamp.
$native   = $handler->getDateTime();
$unixTime = $handler->getTimestamp();

⚠️ The DateTime returned by getDateTime() is the same instance stored internally — modifying it affects the handler.


Helper Shortcuts

Convenience wrappers around addInterval / subInterval.

public function addDays(int $days): self
public function addHours(int $hours): self
public function addMinutes(int $minutes): self
public function subDays(int $days): self
public function subHours(int $hours): self
public function subMinutes(int $minutes): self

All accept positive integers — the direction is encoded in the method name.

(new DateTimeHandler('2024-01-01'))
    ->addDays(7)
    ->subHours(12)
    ->addMinutes(30);

💡 Passing negative numbers will produce invalid DateInterval strings (e.g., P-5D), which PHP will throw on. Use the sub* variants for subtraction.


Static Factories

public static function fromTimestamp(int $timestamp, string $timezone = 'UTC'): self

Rebuild a handler from a Unix timestamp.

$dt = DateTimeHandler::fromTimestamp(1700000000, 'Europe/Paris');
echo $dt->format('Y-m-d H:i:s');

Intermediate Examples

Example 1 — Schedule a reminder 45 minutes before an event

$event = new DateTimeHandler('2024-07-04 18:00:00', 'America/Chicago');

$reminder = (clone $event)->subMinutes(45);
echo $reminder->format('g:i A'); // "5:15 PM"

Example 2 — Count full days between two dates

$start = new DateTimeHandler('2024-01-01');
$end   = new DateTimeHandler('2024-12-31');

$diff = $start->diff($end);
echo "Full days between: {$diff->days}";  // 365

Example 3 — Normalize a user-supplied date to UTC

function toUtc(string $input, string $userTz): string {
    return (new DateTimeHandler($input, $userTz))
        ->getDateTime()
        ->setTimezone(new \DateTimeZone('UTC'))
        ->format('Y-m-d H:i:s');
}

echo toUtc('2024-05-01 10:00', 'Asia/Kolkata'); // "2024-05-01 04:30:00"

Example 4 — Generate the last day of the current month

$lastDay = (new DateTimeHandler())->modify('last day of this month');
echo $lastDay->format('Y-m-d'); // e.g. "2024-06-30"

Example 5 — Build a simple countdown string

$target = new DateTimeHandler('2025-01-01 00:00:00', 'UTC');
$now    = new DateTimeHandler();

$diff = $now->diff($target);

printf(
    "%d days, %d hours, %d minutes remaining",
    $diff->days,
    $diff->h,
    $diff->i
);

Advanced Usage

A. Building a Small Scheduling Service

final class SchedulingService
{
    /** @var DateTimeHandler[] */
    private array $slots = [];

    public function __construct(
        private string $tz,
        private int $intervalMinutes = 30
    ) {}

    public function generateSlots(string $from, string $to): array
    {
        $cursor = new DateTimeHandler($from, $this->tz);
        $end    = new DateTimeHandler($to, $this->tz);

        while ($cursor->getTimestamp() < $end->getTimestamp()) {
            $this->slots[] = clone $cursor;
            $cursor->addMinutes($this->intervalMinutes);
        }

        return $this->slots;
    }

    public function formatAll(string $fmt = 'H:i'): array
    {
        return array_map(fn($s) => $s->format($fmt), $this->slots);
    }
}

$svc = new SchedulingService('Europe/Berlin', 30);
$svc->generateSlots('2024-06-01 09:00', '2024-06-01 12:00');
print_r($svc->formatAll());  // ['09:00','09:30','10:00', ...]

B. Interop with a Legacy DateTime Layer

function legacyToHandler(\DateTime $legacy): DateTimeHandler
{
    return new DateTimeHandler(
        $legacy->format('Y-m-d H:i:s'),
        $legacy->getTimezone()->getName()
    );
}

function handlerToLegacy(DateTimeHandler $handler): \DateTime
{
    // Clone so the caller can't mutate the handler's internal state
    return clone $handler->getDateTime();
}

C. Safe Copy-on-Write Wrapper

Because DateTimeHandler is mutable, wrap it for immutability:

class ImmutableDate
{
    public function __construct(private DateTimeHandler $inner) {}

    public function addDays(int $days): self
    {
        return new self((clone $this->inner)->addDays($days));
    }

    public function format(string $f): string
    {
        return $this->inner->format($f);
    }
}

D. DST-Safe Arithmetic

Because the handler delegates to DateTime, timezone-aware DST transitions are handled automatically:

$dt = new DateTimeHandler('2024-03-10 01:30:00', 'America/New_York');
echo $dt->addHours(2)->format('H:i T'); // "04:30 EDT" (skips 02:00–02:59)

E. Business-Day Calculations

function addBusinessDays(DateTimeHandler $start, int $days): DateTimeHandler
{
    $result = clone $start;
    $added  = 0;

    while ($added < $days) {
        $result->addDays(1);
        $dow = (int) $result->format('N'); // 1 = Mon ... 7 = Sun
        if ($dow <= 5) {
            $added++;
        }
    }

    return $result;
}

Error Handling

Every construction is wrapped in try/catch (\Throwable). Failure produces a DateTimeException with the original message appended:

try {
    $dt = new DateTimeHandler('February 30', 'UTC');
} catch (DateTimeException $e) {
    // "Invalid date/time or timezone: ..."
}

Best practice: treat DateTimeException as a domain-level exception and translate it to your application's error contract (HTTP 422, CLI exit code, etc.).


Best Practices

✅ Do ❌ Don't
Always specify an explicit timezone when it matters Rely on the host's default timezone
Clone before mutating when you need to preserve the original Assume addDays() returns a new instance
Use sub* helpers for subtraction Pass negative numbers to add* helpers
Use getDateTime() sparingly, and clone the result if you'll mutate it Hold long-lived references to the internal DateTime
Catch DateTimeException at service boundaries Let raw parse errors bubble up

Common Pitfalls

1. Mutability Surprise

$a = new DateTimeHandler('2024-01-01');
$b = $a;             // same object!
$b->addDays(5);

echo $a->format('Y-m-d'); // "2024-01-06" — $a changed too!

Fix: use clone $a when you need an independent copy.

2. Negative Interval Strings

(new DateTimeHandler())->addDays(-3);   // ❌ builds "P-3D" → exception
(new DateTimeHandler())->subDays(3);    // ✅ correct

3. Timezone Drift via fromTimestamp

fromTimestamp() first sets the timestamp on a default-configured DateTime, then re-applies the timezone. This works correctly because setTimestamp() is timezone-independent — but always verify your expected output with a quick test in your target timezone.

4. DST Ambiguity

During DST fall-back, certain local times occur twice. PHP's default resolution (using the standard offset) applies. If you need explicit control, use a timezone-aware DateTime directly.

5. diff() Direction

$a->diff($b) returns a result where invert === 1 when $b < $a. Use $diff->invert if your logic must distinguish past vs. future.


Cheat Sheet

use Mlangeni\Machinjiri\Core\Date\DateTimeHandler;

// Create
$dt = new DateTimeHandler('2024-01-01 09:00', 'Africa/Johannesburg');
$dt = DateTimeHandler::fromTimestamp(1700000000, 'UTC');

// Format
$dt->format('Y-m-d\TH:i:sP');    // ISO 8601
$dt->format('l jS F Y');         // "Monday 1st January 2024"

// Modify
$dt->modify('+1 month');
$dt->setDate(2025, 6, 15);
$dt->setTime(14, 30);

// Arithmetic
$dt->addDays(7)->subHours(3)->addMinutes(15);
$dt->addInterval(new DateInterval('P1Y'));
$dt->subInterval(new DateInterval('PT10M'));

// Compare
$diff = $a->diff($b);
echo $diff->days;

// Extract
$native = $dt->getDateTime();
$unix   = $dt->getTimestamp();

Clone this wiki locally