How to convert string to date and datetime with PHP?

Spread the love

Sometimes, we want to convert string to date and datetime with PHP.

In this article, we’ll look at how to convert string to date and datetime with PHP.

How to convert string to date and datetime with PHP?

To date and datetime with PHP, we can use the date_create_from_format function.

For instance, we write

$date = date_create_from_format("m-d-Y", "10-16-2022")->format("Y-m-d");

to call date_create_from_format with the date format string and the date to parse the date string to a date.

Then we call format to return a new date string in the new format.

Y stands for 4 digit year.

m stands for 2 digit month.

d stands for 2 digit date.

Conclusion

To date and datetime with PHP, we can use the date_create_from_format function.

Leave a Reply

Your email address will not be published.