PHP

Start / End of Day, Week, Month

admin by @admin ADMIN
Jun 15, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Snap a DateTime to the start (00:00:00) or end (23:59:59) of its day, week, or month. Builds on DateTimeImmutable for value-safety.
PHP
Raw
<?php
function startOfDay(DateTimeImmutable $d): DateTimeImmutable   { return $d->setTime(0, 0, 0); }
function endOfDay(DateTimeImmutable $d): DateTimeImmutable     { return $d->setTime(23, 59, 59); }
function startOfMonth(DateTimeImmutable $d): DateTimeImmutable { return startOfDay($d->modify('first day of this month')); }
function endOfMonth(DateTimeImmutable $d): DateTimeImmutable   { return endOfDay($d->modify('last day of this month')); }
function startOfWeek(DateTimeImmutable $d, string $start = 'monday'): DateTimeImmutable {
    $dow = (int)$d->format('N');                 // 1=Mon … 7=Sun
    $target = $start === 'sunday' ? 7 : 1;
    $diff   = ($dow - $target + 7) % 7;
    return startOfDay($d->modify("-$diff day"));
}

$now = new DateTimeImmutable('2025-03-12 14:25:00');
echo startOfMonth($now)->format('c');   // 2025-03-01T00:00:00+00:00
echo endOfDay($now)->format('c');       // 2025-03-12T23:59:59+00:00
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.