1. Convert timestamp to date and time
In PHP, UNIX timestamp can be converted to date and time string by calling date () function is implemented. In ThinkPHP5.1, we can use the toDateTimeString() method of the \think\helper\Str class to convert the timestamp into a datetime string.
For example:
use think\helper\Str; $time = 1573679399; echo Str::toDateTimeString($time); // 输出: 2019-11-14 14:03:19
2. Convert date and time to timestamp
In PHP, we can use the strtotime() function to convert date and time characters Convert string to UNIX timestamp. In ThinkPHP5.1, we can use the unixTime() method of the \think\helper\Str class to convert a datetime string into a timestamp.
For example:
use think\helper\Str; $datetime = '2019-11-14 14:03:19'; echo Str::unixTime($datetime); // 输出: 1573679399
3. Time formatting
In PHP, we can use the date() function to format date and time strings change. In ThinkPHP5.1, we can use the dateFormat() method of the \think\helper\Str class to format date and time strings.
For example:
use think\helper\Str; $datetime = '2019-11-14 14:03:19'; echo Str::dateFormat($datetime, 'Y年m月d日 H:i:s'); // 输出: 2019年11月14日 14:03:19
In the dateFormat() method, the first parameter is the date and time string that needs to be formatted, and the second parameter is the format string. Commonly used format strings are as follows:
Date format character | Description |
---|---|
Y | Year (4 digits) |
m | Month (01-12) |
d | Date (01-31) |
H | Hour (00-23) |
i | minutes (00-59) |
s | seconds (00-59) |
4. Time difference calculation
In PHP, we can use the strtotime() function to calculate the time difference between two dates and times. In ThinkPHP5.1, we can use the time() method of the \think\helper\Str class to calculate the time difference between two date times.
For example:
use think\helper\Str; $start = '2019-11-14 14:03:19'; $end = '2019-11-15 16:05:12'; $diff = Str::time($start, $end); echo $diff->format('%a 天 %h 小时 %i 分钟 %s 秒'); // 输出: 1 天 2 小时 1 分钟 53 秒
In the time() method, the first parameter is the start time, and the second parameter is the end time. If you want to calculate the number of days, hours, minutes, seconds, etc. between two times, you can use the format() method of the DateTime object.
The above is the detailed content of How to use time processing functions in ThinkPHP5.1. For more information, please follow other related articles on the PHP Chinese website!