I want to be able to floor a time to the top of the hour, e.g. 14:50:35, becomes 14:00:00.

Either unix timestamp or DateTime/DateTimeImmutable, etc. is OK, but I cannot figure out how to do it. I tried using setTime on DateTimeImmutable but there is no getter for the hour so I cannot simply do something like ->setTime(currenthour, 0, 0), etc.

I assume this can probably be done through some kind of division on the unix timestamp, but I'm not sure. Thx.

ADyson's user avatar

ADyson

63.1k17 gold badges97 silver badges103 bronze badges

user32457645's user avatar

New contributor

user32457645 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

4

You could use the format() function with the hour specifier to give you the current hour:

e.g. ->format("H");

//make a new DateTimeImmutable object and output its current date/time data $dt = new DateTimeImmutable(); echo $dt->format(DATE_ISO8601).PHP_EOL; //get the current hour from the DateTimeImmutable using format() $currenthour = $dt->format("H"); echo $currenthour.PHP_EOL; //make a new DateTimeImmutable with the current hour but the rest of the time data set to 0 $dt2 = $dt->setTime($currenthour, 0, 0); echo $dt2->format(DATE_ISO8601).PHP_EOL;

This will output (for example):

2026-03-10T16:14:42+0000 16 2026-03-10T16:00:00+0000

Demo: https://3v4l.org/5Q8LW

Docs: https://www.php.net/manual/en/datetime.format.php

ADyson's user avatar

2 Comments

Hint: You may use , (multiple arguments) for echo instead of . (concatenation).

2026-03-10T21:44:57.713Z+00:00

Yes, I know that. Does it matter?

2026-03-10T21:55:22.337Z+00:00

I used Carbon as suggested by aynber in the comments under my post.

$now = Carbon::now(); $startOfHour = $now ->startOfHour();

The answer provided by ADyson also seems suitable if you don't want to use libraries. thx everyone :)

user32457645's user avatar

New contributor

user32457645 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.