This article demonstrates how to convert a date from one format to another format in PHP.

1. Using date() and strtotime()

The idea is to use the combination of date() and strtotime() functions to convert a date format to another in PHP. You can convert an English date format string into a Unix timestamp using strtotime(), and then convert that timestamp to another date format string with the date() function. Here, the Unix timestamp equals the total number of seconds since Epoch (January 1, 1970 00:00:00 UTC). For example, the following solution converts a date from yyyy-mm-dd to dd-mm-yyyy format:

Download  Run Code

 
Note that the strtotime() function expects the date string to be in a valid date and time format, otherwise, strtotime() returns false. Therefore, before passing the timestamp to the date() function, you should consider placing an additional check for an invalid format. For example,

Download  Run Code

 
If you just need to print the current date and time in a specific format, you can easily do so with the date() function. For example, the following outputs the current date in dd/mm/yyyy hh:mm:ss format:

Download  Run Code

2. Using DateTime::format() function

Alternatively, you can use the DateTime class for parsing and formatting dates. The DateTime constructor expects a valid date and time format string, and constructs a new DateTime object with it. Then you can pass it to the DateTime::format function to get a date formatted in the given format. Following is a simple example for converting a yyyy-mm-dd date string to dd-mm-yyyy format:

Download  Run Code

 
You can also use the DateTime class to convert a date string in a non-standard format. The idea is to use the DateTime::createFromFormat() function, which parses a datetime string in a specified format and returns a new DateTime object. For example, the following creates a new DateTime object from a date string in dd-mm-yyyy format and uses it to get a date formatted in the yyyy-mm-dd format.

Download  Run Code

 
Or equivalently, you can use the date_create_from_format() and date_format() functions, which are alias of DateTime::createFromFormat() and DateTime::format() functions, respectively.

Download  Run Code

 
Finally, you can use the DateTime object to convert the current date time in a specific format as follows. The following outputs the current date in dd/mm/yyyy hh:mm:ss format:

Download  Run Code

That’s all about converting a date from one format to another format in PHP.