format a date in to the format 'yyyy-mm-dd' in php

To format a date into the 'yyyy-mm-dd' format in PHP, you can use the strftime() function in combination with the strtotime() function.

Here's an example code snippet:

main.php
// Set the timezone
date_default_timezone_set('UTC');

// Create a date object
$date = '2022-03-16';

// Format the date
$formatted_date = strftime('%Y-%m-%d', strtotime($date));

// Output the formatted date
echo $formatted_date; // Output: 2022-03-16
253 chars
12 lines

In the above code, we set the timezone to UTC using date_default_timezone_set() function. Then, we create a date object with the initial date of '2022-03-16'.

Next, we use the strtotime() function to convert the string date into a Unix timestamp, which can be formatted using the strftime() function.

We pass the strftime() function two arguments: the format string of '%Y-%m-%d', which represents 'year-month-day', and the Unix timestamp generated by the strtotime() function.

Finally, we output the formatted date using echo statement.

gistlibby LogSnag