W3jar
284 words
1 minutes

How to Change Date Format in PHP

2024-08-23

In PHP, you can change the format of a date using the date() function, DateTime class, or DateTimeImmutable class. Each method provides different levels of flexibility and functionality.

Using date() Function#

The date() function formats a local date and time, using a specified format string. Here’s how you can use it:

<?php
// Original date string
$dateString = "2024-08-23";

// Convert to a timestamp
$timestamp = strtotime($dateString);

// Format the date
$formattedDate = date("d-m-Y", $timestamp);

echo $formattedDate; // Output: 23-08-2024
?>

Format String Options#

  • "Y": 4-digit year (e.g., 2024)
  • "m": 2-digit month (e.g., 08)
  • "d": 2-digit day of the month (e.g., 23)
  • "H": 24-hour format of an hour (e.g., 14)
  • "i": Minutes with leading zeros (e.g., 05)
  • "s": Seconds with leading zeros (e.g., 09)

Using DateTime Class#

The DateTime class provides more flexibility and is recommended for complex date manipulations. Here’s how you can use it:

<?php
// Create a DateTime object from a date string
$date = new DateTime("2024-08-23");

// Format the date
$formattedDate = $date->format("d/m/Y");

echo $formattedDate; // Output: 23/08/2024
?>

Using DateTimeImmutable Class#

The DateTimeImmutable class works similarly to DateTime, but it does not modify the original object; instead, it returns a new instance with the applied changes. Here’s an example:

<?php
// Create a DateTimeImmutable object from a date string
$date = new DateTimeImmutable("2024-08-23");

// Format the date
$formattedDate = $date->format("Y.m.d");

echo $formattedDate; // Output: 2024.08.23
?>

Custom Formats#

You can use any format string supported by the date() function or DateTime::format(). Here are a few examples:

  • "Y-m-d": 2024-08-23
  • "l, F j, Y": Friday, August 23, 2024
  • "M d, Y H:i:s": Aug 23, 2024 14:05:00

Conclusion#

  • date() function: Simple and useful for basic formatting.
  • DateTime class: More powerful and flexible for date manipulation.
  • DateTimeImmutable class: Similar to DateTime, but immutable.

Choose the method based on your needs, whether for simple formatting or more complex date operations.