Home > Article > Backend Development > How to convert date format to text in php
PHP is a widely used scripting language and it is very common in web development. Dates are also an important component in web development. In this post, we will learn how to convert date format to text using PHP.
In PHP, we can use the date() function to convert date format to text. The following are some commonly used date formats:
Using these formats, we can convert the date format to text through the date() function, as shown below:
$date = "2021-04-23"; echo date("Y-m-d", strtotime($date)); //输出2021-04-23
In this example, we pass a date string to the strtotime() function, And use the date() function to format it into year-month-day format.
If we want to convert the date format to more friendly text, we can add text in the format string as follows:
$date = "2021-04-23"; echo date("Y年m月d日 (D)", strtotime($date)); //输出2021年04月23日 (Fri)
In this example, we will format the date Set it to the format of "year-month-day (day of the week)" and use the text "year", "month", "day" and brackets to make it more friendly. The output result is "Friday, April 23, 2021" ".
We can also use PHP's timestamp function to calculate the difference between dates. The timestamp represents the number of seconds since January 1, 1970. We can use the time() function to get the current timestamp as follows:
$now = time(); //获取当前时间戳 echo $now; //输出当前时间戳
Additionally, we can use the strtotime() function to convert the date string to a timestamp:
$date = "2021-04-23"; $timestamp = strtotime($date); //将日期字符串转换为时间戳 echo $timestamp; //输出时间戳
Once we With the timestamps of two dates, we can calculate the difference between them as follows:
$date1 = "2021-04-23"; $date2 = "2021-06-01"; $timestamp1 = strtotime($date1); $timestamp2 = strtotime($date2); $diff = $timestamp2 - $timestamp1; echo "两个日期相差" . round($diff / (60*60*24)) . "天";
In this example, we calculated the timestamps of two dates and then calculated the difference between them difference. Since the difference is in seconds, we convert it to days and round using the round() function, the output is "The two dates differ by 39 days".
In conclusion, using PHP, we can easily convert date format to text and calculate the difference between dates. These features are very useful in web development, I hope this article will be helpful to you.
The above is the detailed content of How to convert date format to text in php. For more information, please follow other related articles on the PHP Chinese website!