PHP to format a date in ISO 8601


PHP: Format a Date in ISO 8601

<?php
// Create a DateTime object
$date = new DateTime();

// Format the date in ISO 8601 format
$isoDate = $date->format('Y-m-d\TH:i:s.u\Z');

// Print the ISO 8601 date
echo $isoDate;
?>

This code snippet demonstrates how to format a date in ISO 8601 format using the DateTime class in PHP. Here’s how the code works:

  1. We start by creating a new DateTime object. This object represents the current date and time.
  2. The format() method is used to format the date. The format string 'Y-m-d\TH:i:s.u\Z' is used to specify the ISO 8601 format. This format consists of the following components:
    • Y: Year (e.g., 2023).
    • m: Month (e.g., 03).
    • d: Day of the month (e.g., 15).
    • T: Separator between the date and time.
    • H: Hour (24-hour format) (e.g., 14).
    • i: Minute (e.g., 30).
    • s: Second (e.g., 59).
    • u: Microseconds (e.g., 123456).
    • Z: Time zone offset (e.g., +00:00).
  3. Finally, the formatted date is printed to the console.

Example Output:

2023-03-15T14:30:59.123456+00:00