Time Formatting Parsing in PHP

PHP supports date and time formatting and parsing via built-in functions and the DateTime class.

<?php

// Here's a basic example of formatting a time
// according to RFC3339, using the DateTime class.
$t = new DateTime();
echo $t->format(DateTime::RFC3339) . "\n";

// Time parsing uses the same format as formatting.
$t1 = DateTime::createFromFormat(DateTime::RFC3339, "2012-11-01T22:08:41+00:00");
echo $t1->format(DateTime::RFC3339) . "\n";

// format() and createFromFormat() use example-based layouts.
// You can use predefined constants or custom format strings.
echo $t->format("g:iA") . "\n";
echo $t->format("D M j H:i:s Y") . "\n";
echo $t->format("Y-m-d\TH:i:s.uP") . "\n";

$form = "g i A";
$t2 = DateTime::createFromFormat($form, "8 41 PM");
echo $t2->format(DateTime::RFC3339) . "\n";

// For purely numeric representations you can also
// use standard string formatting with the extracted
// components of the time value.
printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
    $t->format("Y"), $t->format("m"), $t->format("d"),
    $t->format("H"), $t->format("i"), $t->format("s"));

// createFromFormat() will return false on malformed input.
$ansic = "D M j H:i:s Y";
$result = DateTime::createFromFormat($ansic, "8:41PM");
var_dump($result);

Running this PHP script would produce output similar to:

2023-06-15T12:34:56+00:00
2012-11-01T22:08:41+00:00
12:34PM
Thu Jun 15 12:34:56 2023
2023-06-15T12:34:56.123456+00:00
0000-08-41T20:41:00+00:00
2023-06-15T12:34:56-00:00
bool(false)

In PHP, date and time formatting is handled primarily through the DateTime class and its methods. The format() method is used for formatting dates, while createFromFormat() is used for parsing.

PHP uses format codes that are different from those in other languages. For example:

  • Y-m-d for year-month-day
  • H:i:s for hour:minute:second
  • P for the timezone offset

PHP also provides several predefined date format constants like DateTime::RFC3339.

For parsing, createFromFormat() returns false if it fails to parse the input string according to the given format. You can use DateTime::getLastErrors() to get more detailed error information.

Remember that PHP’s date and time functions are generally not as strict as some other languages. For example, "8 41 PM" can be parsed even though it doesn’t include date information. In such cases, the missing parts are filled with default values.

PHP’s flexibility with date and time can be both an advantage and a potential source of bugs, so it’s important to be explicit about your date formats and to validate input thoroughly when working with dates and times.