Signup/Sign In
PUBLISHED ON: AUGUST 4, 2021

How to convert a date from yyyy-mm-dd to dd-mm-yyyy format in PHP?

Answer: Using strtotime() function

We can convert a date from yyyy-mm-dd to dd-mm-yyyy format by using the PHP strtotime() and date() function.

The strtotime() function is a predefined function offered by the PHP, which converts the string date and time into a UNIX timestamp then by using the date() function, we can convert the timestamp into the desired date format.

Example: Format using strtotime() function

In the given example, we have converted a date from yyyy-mm-dd format to dd-mm-yyyy format using the strtotime() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Convert a date from yyyy-mm-dd to dd-mm-yyyy format</title>
</head> 
<body>  
	<?php
	$date = "2021-08-02";	 
	$timestamp = strtotime($date);	 
	$new_date = date("d-m-Y", $timestamp);
	echo $new_date;
	?>
</body>  
</html>


02-08-2021

Using DateTime() function

We can also convert a date from yyyy-mm-dd to dd-mm-yyyy format by using DateTime() function and used the format function that returns a new formatted date according to the specified format.

Example: Using DateTime() function

In the given example, we have converted a date format from yyyy-mm-dd to dd-mm-yyyy using DateTime() function.

<!DOCTYPE html>  
<html> 
<head>
	<title>Convert a date from yyyy-mm-dd to dd-mm-yyyy format</title>
</head> 
<body>  
	<?php
		$date = "2021-08-02";		 
		$new_date = new DateTime($date);
	    echo $new_date->format('d-m-Y');
	?>
</body>  
</html> 


02-08-2021

Conclusion

In this lesson, we have learned how to convert the date format from yyyy-mm-dd to dd-mm-yyyy in PHP. We used a predefined function strtotime() that first converts the date format into the UNIX timestamp, and then using the date() function, we can convert the time stamp into the desired date format.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.