On 2022-08-21 3:59 PM, Rowan Tommins wrote:
Could you give some quick examples of when these functions would give different answers, and why someone might need / want the "floor" variants?
My hobby is fiddling with calendrical calculations, and, if you need a perfect subject area where the floor technique is needed, this is it. Here is an easy, contrived example of a program that takes a UNIX timestamp and returns the day of the week. ``` <?php function day_of_week(int $unix_timestamp): string { $names = [ "Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday" ]; $array_key = intdiv($unix_timestamp, 86400) % 7; return $names[$array_key]; } echo day_of_week(strtotime("22 August 2022")) . "\n"; // Monday echo day_of_week(strtotime("26 June 2022")) . "\n"; // Sunday echo day_of_week(strtotime("9 June 2001")) . "\n"; // Saturday echo day_of_week(strtotime("10 June 1996")) . "\n"; // Monday echo day_of_week(strtotime("14 April 1928")) . "\n"; // Saturday ?> ``` For the first four instances, the function works as intended since the timestamps are non-negative numbers. However, for the fifth example, since the date is before 1970, the timestamp is going to be negative resulting in an ostensible array key which will also be negative. The floor technique would instead return a positive array key.
I clicked through to the Python History article, and Guido gives the example of taking a timestamp module 86400, and says that with the "truncation" technique it gives "a meaningless result", but doesn't actually illustrate that result, so I'm struggling to picture exactly what each algorithm does.
Here’s what Guido is saying. If I run this program… ``` <?php $dates = [ "22 August 2022 1:46 AM", "26 June 2022 1:46 AM", "9 June 2001 1:46 AM", "10 June 1996 1:46 AM", "14 April 1928 1:46 AM" ]; foreach ($dates as $date) { $seconds = strtotime($date) % 86400; echo "It’s been " . number_format($seconds, "0", ".", ",") . " seconds since midnight.\n"; } ?> ``` …since the time of the day for each of these dates is the same (i.e., 1:46 AM), it *should* calculate 6,360 seconds since midnight for each instance. It does this correctly for the first four instances, but the fifth instance reports -80,040 seconds—a meaningless result. The floor technique would return the same result as the others. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php