PHP is a popular server-side programming language that provides some powerful features that make working with dates and times relatively easy. In this article, we will look at how to convert date types in PHP.
First, let’s take a look at how to format the date into the style we want. In PHP, we can use the date() function to format dates. This function accepts two parameters: one is the date format and the other is the date to be formatted. The following are several commonly used date formats:
In addition to these, we can also use other format to display date, time, time zone, etc. Here are some advanced date formats:
Here is some sample code for formatting dates:
//输出当前日期和时间,格式为: 年-月-日 小时:分钟:秒 echo date("Y-m-d H:i:s"); //输出当前星期,格式为: 星期几 echo date("l"); //输出当前时间的上午或下午,格式为: 上午或下午 echo date("A"); //将一个时间戳格式化为日期,格式为: 年-月-日 echo date("Y-m-d", strtotime("2021-08-30"));
Another common date conversion is to Convert string to date. For example, if we get date information from a database or other source, it will usually be provided as a string. We can convert string to date using strtotime() function in PHP.
The strtotime() function supports various time formats and can convert characters into corresponding timestamps and format them as needed. The following is some sample code:
//将字符串转换为日期,格式为: 年-月-日 $dateString = '2021-08-30'; $date = date("Y-m-d", strtotime($dateString)); echo $date; //将字符串转换为日期时间,格式为: 年-月-日 小时:分钟:秒 $dateString = '2021-08-30 13:45:30'; $date = date("Y-m-d H:i:s", strtotime($dateString)); echo $date;
In PHP, we can use the date() function and strtotime() function to add and subtract dates. Among them, the date() function can format dates, and the strtotime() function can convert strings to dates.
These two functions can be used together to complete date addition and subtraction operations very conveniently. Here is some sample code:
//加一周 $dateString = '2021-09-05'; $date = date("Y-m-d", strtotime($dateString . "+1 week")); echo $date; //减一个月 $dateString = '2021-08-30'; $date = date("Y-m-d", strtotime($dateString . "-1 month")); echo $date; //加一天 $dateString = '2021-08-30'; $date = date("Y-m-d", strtotime($dateString . "+1 day")); echo $date;
In PHP, we can use the date() function to format the date into the style we want. In addition, we can also use the strtotime() function to convert a string into a date, or use the date() and strtotime() functions combined to add and subtract dates. These features make it relatively easy to handle dates and times in PHP, which is very commonly used when developing web applications.
The above is the detailed content of How to convert date type in PHP. For more information, please follow other related articles on the PHP Chinese website!