Repository navigation
Date and Time
DateTimeHandleris a lightweight, chainable wrapper around PHP's built-inDateTimeclass. It provides:
- Fluent interface – chain multiple operations together
- Explicit timezone handling – every instance is timezone-aware
-
Type-safe exception handling – converts native
ThrowableintoDateTimeException -
Convenience helpers – add/subtract days, hours, and minutes without manually crafting
DateIntervalstrings - Timestamp interoperability – static factory for reconstructing from Unix timestamps
The class lives in the namespace:
Mlangeni\Machinjiri\Core\Dateuse 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.
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.
Every handler is created with an explicit timezone (default UTC). The timezone is used at construction and preserved through all mutations.
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();
}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');public function format(string $format): stringReturns 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 timestamppublic function modify(string $modifier): selfAccepts any string valid for DateTime::modify(). Returns $this.
$handler->modify('+1 week');
$handler->modify('last day of this month');
$handler->modify('next Monday');public function addInterval(DateInterval $interval): self
public function subInterval(DateInterval $interval): selfAdd or subtract a native DateInterval.
$interval = new DateInterval('P1Y2M3D');
$handler->addInterval($interval);
$handler->subInterval(new DateInterval('PT45M'));public function diff(DateTimeHandler $other): DateIntervalReturns 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 < $apublic 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, 2025public function getDateTime(): DateTime
public function getTimestamp(): int-
getDateTime()returns the underlyingDateTimeobject (useful for interoperability). -
getTimestamp()returns the Unix timestamp.
$native = $handler->getDateTime();
$unixTime = $handler->getTimestamp();
⚠️ TheDateTimereturned bygetDateTime()is the same instance stored internally — modifying it affects the handler.
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): selfAll 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
DateIntervalstrings (e.g.,P-5D), which PHP will throw on. Use thesub*variants for subtraction.
public static function fromTimestamp(int $timestamp, string $timezone = 'UTC'): selfRebuild a handler from a Unix timestamp.
$dt = DateTimeHandler::fromTimestamp(1700000000, 'Europe/Paris');
echo $dt->format('Y-m-d H:i:s');$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"$start = new DateTimeHandler('2024-01-01');
$end = new DateTimeHandler('2024-12-31');
$diff = $start->diff($end);
echo "Full days between: {$diff->days}"; // 365function 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"$lastDay = (new DateTimeHandler())->modify('last day of this month');
echo $lastDay->format('Y-m-d'); // e.g. "2024-06-30"$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
);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', ...]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();
}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);
}
}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)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;
}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.).
| ✅ 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 |
$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.
(new DateTimeHandler())->addDays(-3); // ❌ builds "P-3D" → exception
(new DateTimeHandler())->subDays(3); // ✅ correctfromTimestamp() 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.
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.
$a->diff($b) returns a result where invert === 1 when $b < $a. Use $diff->invert if your logic must distinguish past vs. future.
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();Machinjiri Docs
- Home
- Learn
- Build
-
Tutorials
- Routing
- Controllers and Middleware
- Views and Templates
- Database ORM
- Eloquent Database ORM
- Errors and Exceptions
- Forms and Validation
- Http
- Events and Logging
- Services and DI
- Security
- Authentication
- Caching
- File System
- Date and Time
- Debugging
- Queue and Jobs
- Task Scheduling
- Transport (Mail, SMS)
- LDAP
- Notifications
- Webhooks
- UUID Generations
- Terminal
- Helper Function
- Reference