Home > Backend Development > PHP Tutorial > How to Convert 'yyyy-mm-dd' to 'dd-mm-yyyy' Date Format in PHP Without Using SQL?

How to Convert 'yyyy-mm-dd' to 'dd-mm-yyyy' Date Format in PHP Without Using SQL?

Linda Hamilton
Release: 2024-12-26 08:57:10
Original
987 people have browsed it

How to Convert

Convert a Date Format in PHP

You may encounter a scenario where you need to reformat a date from yyyy-mm-dd to dd-mm-yyyy without using SQL. However, the date function in PHP typically requires a timestamp, and extracting a timestamp from a string can be challenging.

To overcome this hurdle, you can utilize the following approach:

use DateTime;
use DateTimeZone;

$originalDate = "2010-03-21";
$timestamp = strtotime($originalDate); // Convert to a timestamp

// Option 1: Using DateTime
$dt = new DateTime();
$dt->setTimestamp($timestamp);
$newDate = $dt->format('d-m-Y'); // Reformat the date

// Option 2: Using date() with strtotime()
$newDate = date("d-m-Y", $timestamp);
Copy after login

The strtotime() function converts the string representation of the date into a timestamp. Subsequently, you can use either DateTime or date() to reformat the date according to your desired format.

Note:

While this approach provides a simple solution, it might not be suitable for all conversion scenarios. For more complex date conversions, consider using the DateTime class for parsing and formatting.

The above is the detailed content of How to Convert 'yyyy-mm-dd' to 'dd-mm-yyyy' Date Format in PHP Without Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template