Home > Backend Development > PHP Tutorial > How Can I Convert YYYY-MM-DD to DD-MM-YYYY Date Formats in PHP?

How Can I Convert YYYY-MM-DD to DD-MM-YYYY Date Formats in PHP?

Linda Hamilton
Release: 2025-01-05 09:47:40
Original
525 people have browsed it

How Can I Convert YYYY-MM-DD to DD-MM-YYYY Date Formats in PHP?

Converting Date Formats in PHP

Users often encounter the need to convert dates between different formats. In PHP, converting a date from YYYY-MM-DD to DD-MM-YYYY poses a challenge, as the date function expects a timestamp. Here's how to tackle this issue:

Using strtotime() and date() Functions

To convert the date format without relying on SQL, you can utilize the strtotime() and date() functions. This approach involves the following steps:

  1. Use strtotime() to convert the original date string (e.g., "2010-03-21") into a Unix timestamp.
  2. Use date() to format the timestamp into the desired output format (e.g., "d-m-Y").
$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

// Output: 21-03-2010
Copy after login

Alternative Approach: DateTime Class

While the above solution is efficient for simple conversions, complex date manipulations require a more robust approach. Here, the DateTime class comes into play:

$dt = new DateTime($originalDate);
$newDateFormat = $dt->format("d-m-Y");

// Output: 21-03-2010
Copy after login

The above is the detailed content of How Can I Convert YYYY-MM-DD to DD-MM-YYYY Date Formats in PHP?. 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