ARTICLE AD BOX
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.
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+0000Demo: https://3v4l.org/5Q8LW
2 Comments
Hint: You may use , (multiple arguments) for echo instead of . (concatenation).
2026-03-10T21:44:57.713Z+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 :)
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.
Explore related questions
See similar questions with these tags.


