DateTime class vs. native PHP date-functions

后端 未结 3 1130
无人及你
无人及你 2020-11-30 13:23

The DateTime class sure has some handy methods and seems overall superior to the native PHP date functions like strtotime, mktime and strftim

3条回答
  •  情书的邮戳
    2020-11-30 14:20

    Using DateTime() makes the code more readable compared to the procedural approach of strtotime(), etc. functions.

    if( strtotime( date( 'm/d/Y', strtotime( $strStartDate ) ) ) > strtotime( date( 'm/d/Y', strtotime( '+6 month', strtotime( $strEndDate ) ) ) ) ) {
    

    vs

    if( new DateTime( $strStartDate ) > ( new DateTime( $strEndDate ) )->modify( '+6 month' ) ) {
    

    On Windows 64 bit development machines, PHP is still 32bit. It will give your weird results for dates beyond Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC

    echo ( new DateTime( '20 Jan 2038' ) )->format( 'm/d/Y' ) . PHP_EOL; // gives 01/20/2038
    echo strtotime( '20 Jan 2038' ); // returns false
    

    https://www.php.net/manual/en/function.strtotime.php#refsect1-function.strtotime-notes

    Note: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Prior to PHP 5.1.0, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems. For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent approximately 293 billion years in either direction.


    I am not sure if daylight saving is properly handled with native date time functions.


    I would recommend using DateTime() functions over native date time functions.

提交回复
热议问题