About the implementation code of PHP time function encapsulation

不言
Release: 2023-04-03 11:34:01
Original
1887 people have browsed it

The content shared with you in this article is about the implementation code of PHP time function encapsulation. The content is of great reference value. I hope it can help friends in need.

1. The number of days between two dates

function dateDiff($time1, $time2, $absolute = false)
{
    $time1 = (($temp = strtotime($time1)) ? $temp : $time1);
    $time2 = (($temp = strtotime($time2)) ? $temp : $time2);
    $temp = (strtotime(date('Ymd', $time1)) - strtotime(date('Ymd', $time2))) / 86400;
    return $absolute ? abs($temp) : $temp;
}
Copy after login

PHP’s own function date_diff needs to pass in a DateTime object, which is troublesome. The above method returns the number of days between the two times/timestamps. The idea is: if it is time, convert the time into a timestamp, format it to 0 o'clock on the day and then convert it back to a timestamp, subtract and divide by 86400. Of course, if the method is only the number of days between the two timestamps, the first line and the second line The conversion timestamp code can be removed. There is a difference of 1 day between 2018-01-01 23:59:59 and 2018-01-02 00:00:00. 2018-01-01 00:00:00 and 2018-01-02 23:59:59 are also 1 day apart.

2. Current time in milliseconds

function msec()
{
    return sprintf('%.0f', microtime(true) * 1000);
}
Copy after login

PHP does not have a function that directly returns milliseconds. Here, microseconds are formatted to produce microseconds.

Related recommendations:

Implementation of weak type conversion in PHP

##code of how PHP uploads images to the database for display

The above is the detailed content of About the implementation code of PHP time function encapsulation. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template