php-standard-library/date-time
Immutable, timezone-aware DateTime types for PHP. Provides Duration, Period, and Interval helpers for safer date/time arithmetic and ranges, designed as a standard-library style package with clear docs and contribution links.
Installation
composer require php-standard-library/date-time
Add to composer.json under require or require-dev if needed.
First Use Case: Creating a Timezone-Aware DateTime
use PhpStandardLibrary\DateTime\DateTime;
$now = DateTime::now('America/New_York');
echo $now->format('Y-m-d H:i:sP'); // Outputs: 2026-03-20 14:30:45-04:00
Key Classes to Explore
DateTime (immutable, timezone-aware)Duration (e.g., Duration::fromHours(2.5))Period (e.g., Period::fromDays(7))Interval (e.g., Interval::fromStartEnd($start, $end))Where to Look First
tests/ directory for usage examplesREADME.md for basic API docs (if provided)$nyTime = DateTime::now('America/New_York');
$londonTime = $nyTime->inTimezone('Europe/London');
$diff = $nyTime->diff($londonTime); // Duration object
$tomorrow = $now->add(Duration::fromDays(1));
$yesterday = $now->subtract(Period::fromDays(1));
$start = DateTime::fromFormat('Y-m-d', '2026-01-01');
$end = DateTime::fromFormat('Y-m-d', '2026-01-31');
$interval = Interval::fromStartEnd($start, $end);
$daysInInterval = $interval->days(); // 31
$meetingDuration = Duration::fromHours(1.5);
$endTime = $now->add($meetingDuration);
$weeklyReport = Period::fromWeeks(1);
$nextRun = $now->add($weeklyReport);
Laravel Carbon Compatibility
Convert between DateTime and Carbon for existing apps:
$carbon = Carbon::instance($dateTime);
$dateTime = DateTime::fromCarbon($carbon);
Validation
Use with Laravel’s Validator for strict date/time checks:
$validator->rule('due_date', function ($attribute, $value, $fail) {
$date = DateTime::fromFormat('Y-m-d', $value);
if ($date->isBefore($now)) {
$fail('Date must be in the future.');
}
});
API Responses
Serialize DateTime objects to ISO 8601 strings:
return response()->json(['scheduled_at' => $dateTime->toAtomString()]);
Database Storage Store as UTC in the database, convert on retrieval:
$utcTime = $dateTime->inTimezone('UTC');
$storedAt = $utcTime->format('Y-m-d H:i:s');
Immutability
// ❌ Loses reference
$now->add(Duration::fromDays(1))->format('Y-m-d');
// ✅ Correct
$tomorrow = $now->add(Duration::fromDays(1));
Timezone Handling
// ❌ Ambiguous
$dateTime = DateTime::now();
// ✅ Explicit
$dateTime = DateTime::now('UTC');
Duration vs. Period
Duration is for time-based intervals (e.g., "2 hours").Period is for calendar-based intervals (e.g., "1 week").// ❌ Avoid
$now->add(Period::fromHours(24)); // Throws exception
Leap Seconds
Legacy Carbon Dependencies
createFromFormat, replicate logic:
// Instead of:
Carbon::createFromFormat('d/m/Y', '31/12/2025');
// Use:
DateTime::fromFormat('d/m/Y', '31/12/2025', 'UTC');
Inspect Timezones
echo $dateTime->timezone()->getName(); // Debug timezone
Format for Clarity
echo $dateTime->format('Y-m-d H:i:sP e'); // Includes timezone offset and name
Compare Objects
if ($dateTime1->equals($dateTime2)) {
// ...
}
Use toString() for Debugging
echo $duration->toString(); // "PT2H30M" for 2.5 hours
Custom Formatters Extend the library by creating a formatter trait:
trait CustomFormatter {
public function toLaravelFormat(): string {
return $this->format('Y-m-d H:i:s.u');
}
}
Add Validation Rules Create a Laravel rule for business logic:
use PhpStandardLibrary\DateTime\DateTime;
class FutureDateRule extends Rule {
public function passes($attribute, $value) {
$date = DateTime::fromFormat('Y-m-d', $value);
return $date->isAfter(DateTime::now());
}
}
Event Dispatching Trigger events on date transitions:
$dateTime->onNextDay(function () {
event(new DailyTaskScheduled());
});
Database Observers Use with Laravel’s model observers to auto-convert timestamps:
class DateTimeObserver {
public function saving(Model $model) {
if ($model->usesDateTimeAttribute('scheduled_at')) {
$model->scheduled_at = $model->scheduled_at->inTimezone('UTC');
}
}
}
Testing Utilities Create helper methods for tests:
function createTestDateTime(string $date, string $timezone = 'UTC'): DateTime {
return DateTime::fromFormat('Y-m-d', $date, $timezone);
}
How can I help you explore Laravel packages today?