Home  >  Article  >  Backend Development  >  How to convert timestamp from current time in php

How to convert timestamp from current time in php

PHPz
PHPzOriginal
2023-03-29 10:12:08373browse

In PHP, the timestamp is a typical integer, representing the number of seconds from January 1, 1970 00:00:00 (Coordinated Universal Time (UTC)) to the current time. We can use the time() function to get the current timestamp.

However, PHP also allows converting timestamps to more readable date and time formats. When we need to convert a date or time to a timestamp, we can use strtotime( ) function.

Now, let’s explore how to convert the current time to a timestamp in PHP.

First, we need to understand the time() function. This function will return the current Unix time Stamp, that is, the number of seconds from 00:00:00 (UTC) on January 1, 1970 to the present.

The following is a sample code that demonstrates how to use the time() function in PHP to obtain the timestamp of the current time:

$current_timestamp = time();
echo $current_timestamp;

Running the above code will output the current Unix timestamp.

However, when we need to convert a date or time to a Unix timestamp, we need to use the strtotime() function. This function takes a string representing a date or time and converts it to a Unix timestamp.

Here is some sample code that demonstrates how to use the strtotime() function to convert a date string to a UNIX timestamp:

// 转换 '2020-08-01' 为 Unix 时间戳
$timestamp = strtotime('2020-08-01');
echo $timestamp;

// 转换 '2020-08-01 12:00:00' 为 Unix 时间戳
$timestamp = strtotime('2020-08-01 12:00:00');
echo $timestamp;

// 获取明天的 Unix 时间戳
$timestamp = strtotime('+1 day');
echo $timestamp;

In the above code, the first example converts the date string' 2020-08-01' converted to Unix timestamp. The second example converts the date string '2020-08-01 12:00:00' to a Unix timestamp. The third example gets tomorrow's Unix timestamp.

In short, in PHP, you can get the Unix timestamp of the current time through the time() function, or you can use the strtotime() function to convert a date string into a Unix timestamp. These functions can help us operate time and date in PHP and handle related business logic.

The above is the detailed content of How to convert timestamp from current time in php. 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