Home >PHP Framework >ThinkPHP >How to query and convert timestamps in ThinkPHP

How to query and convert timestamps in ThinkPHP

PHPz
PHPzOriginal
2023-04-17 09:48:562098browse

ThinkPHP is an excellent PHP framework that is widely used in website development. In actual development, we often need to query the timestamps stored in the database and convert them into an easy-to-understand date and time format. This article will introduce how to query and convert timestamps in the ThinkPHP framework.

Query timestamp

In ThinkPHP, you can query timestamp in the following two ways:

Method 1: Use timestamp query conditions

$map['create_time'] = ['between', [strtotime('2019-01-01'),strtotime('2019-12-31 23:59:59')]];
$list = Db::name('table_name')->where($map)->select();

In the above code, the create_time key in the $map array is the name of the field in the database that stores the timestamp. strtotime() The function converts the specified date and time into a timestamp, and then queries the data within the specified time period through the between condition.

Method 2: Use query constructor

$list = Db::name('table_name')
            ->whereTime('create_time', 'between', ['2019-01-01', '2019-12-31 23:59:59'])
            ->select();

In the above code, the whereTime() function can pass a timestamp or date and time string according to different query conditions Generate SQL statements.

Convert timestamp

To convert timestamp to date and time format, ThinkPHP provides the following methods:

Method 1: Use the date() function

$time = time(); // 获取当前时间戳
$date = date('Y-m-d H:i:s', $time); // 转换为日期时间格式

In the above code, the date() function can convert the timestamp into a date and time string in the specified format.

Method 2: Use the datetime() function

$list = Db::name('table_name')->select();
foreach($list as $item){
    $item['create_time'] = datetime($item['create_time']);
}
echo json_encode($list);

In the above code, the datetime() function can convert the timestamp field value into a date time format and returns the converted string. In actual development, the converted date and time format can be used for display or output.

The above is the method of querying and converting timestamps in the ThinkPHP framework. Through the above method, we can easily convert between timestamp and date and time formats to speed up development efficiency.

The above is the detailed content of How to query and convert timestamps in ThinkPHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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