How to convert a date in php?

Member

by jasen , in category: PHP General , 6 months ago

How to convert a date in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 6 months ago

@jasen 

To convert a date in PHP, you can use the strtotime function along with the date function. Here's an example:

1
2
3
4
5
$dateString = "2021-07-20"; // Your date string in 'YYYY-MM-DD' format
$timestamp = strtotime($dateString); // Convert the date string to a Unix timestamp

$newDateFormat = date("F j, Y", $timestamp); // Convert the timestamp to a new date format
echo $newDateFormat; // Output: July 20, 2021


In the code above, we first use strtotime to convert the date string to a Unix timestamp. This is a standard way of representing dates and times in PHP.


Then we use the date function to convert the timestamp to a new date format. In this example, we use the format "F j, Y" which displays the month name, day, and year (e.g. "July 20, 2021").


You can change the format string passed to the date function to achieve different date formats as needed. You can refer to the PHP documentation for more options and format specifiers available with the date function.