PHP language is a very popular server-side scripting language that can quickly develop large-scale web applications and websites. Among them, timestamp is a very important concept in web development. It is a number that represents date and time.
In PHP, we can use some functions to convert timestamps and years, months and days. The specific implementation is as follows:
We can use PHP's strtotime() function to convert date and time into timestamp. This function accepts a datetime string and returns an integer containing the UNIX timestamp (from January 1, 1970).
For example, the following code converts the string "2022-06-15 14:30:00" into a timestamp:
<?php $date_str = '2022-06-15 14:30:00'; $timestamp = strtotime($date_str); echo $timestamp; ?>
The output result is:
1655334600
The date() function can be used in PHP to convert timestamps to dates and times in a specified format. This function accepts two parameters: the first parameter is a string in datetime format, and the second parameter is a timestamp. This function returns a string containing the formatted date and time.
For example, the following code converts the timestamp 1655334600 to the date and time format of "2022-06-15 14:30:00":
<?php $timestamp = 1655334600; $date_str = date('Y-m-d H:i:s', $timestamp); echo $date_str; ?>
The output result is:
2022-06-15 14:30:00
If we already have a string in the format of "YYYY-MM-DD", we can use strtotime( ) function to convert it to a timestamp. This function will parse a date string and return the corresponding UNIX timestamp.
For example, the following code converts the string "2022-06-15" into a timestamp:
<?php $date_str = '2022-06-15'; $timestamp = strtotime($date_str); echo $timestamp; ?>
The output result is:
1655299200
You can also use the date() function in PHP to convert the timestamp into the format of year, month and day. In this case, we just need to pass "Y-m-d" as the first parameter.
For example, the following code converts the timestamp 1655299200 into the year, month and day format of "2022-06-15":
<?php $timestamp = 1655299200; $date_str = date('Y-m-d', $timestamp); echo $date_str; ?>
The output result is:
2022-06-15
Summary
In PHP, conversion between timestamp and datetime formats is very easy to implement. We can use the strtotime() function to convert date and time to a timestamp, or use the date() function to convert a timestamp to a date and time in a specified format. At the same time, we can also use the strtotime() function to convert a string in year, month, and day format into a timestamp, or use the date() function to convert a timestamp into a string in year, month, and day format. These functions not only reduce our programming workload, but also make our code clearer and easier to read.
The above is the detailed content of How to convert timestamp and year, month and day in php. For more information, please follow other related articles on the PHP Chinese website!