4

Given any unix-timestamp T, I want to fetch the timestamp of the midnight before T.

The given timestamp can be any integer: now, today, (not too far[]) in the future or (not too far[]) in the past.

Is there a cleaner way then (pseudocode):

<?php $midnight = strtotime("{date('d',$ts)}-{date('m',$ts)}-{date('Y', $ts)} midnight"); ?> 

Thanks.

[*] somewhere between 1990 and 2020.

3 Answers 3

6

I would do it as

$midnight = strtotime(date('Y-m-d',$ts).' 00:00:00'); 

...but whether that is cleaner/better is debatable...

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was afraid that the route via strtotime was the only "pragmatic" approach. Yours is the most clean of these.
3

Since a full day is 86400 seconds, you should be able to do this:

$midnight = $ts - $ts%86400; 

However, this wouldn't consider any leap seconds that might have been applied to the unix timestamp.

This would be a lot more performant than using strtotime but would probably only matter if you would do this in big tight loops.

Comments

1

Et voila'

<?php $midnight = strtotime(date('d-m-Y',$ts)); echo date('d-m-Y H:i:s',$ts); // output 03-11-2011 12:43:41 echo date('d-m-Y H:i:s',$midnight); // ouput 03-11-2011 00:00:00 ?> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.