PHP:
Converting a date into a string
How to:
In PHP, the date()
function formats a timestamp to a more readable string. The DateTime
object serves a similar purpose with its format()
method. Here’s how they look in practice:
<?php
// Using date() function
echo date('Y-m-d H:i:s') . "\n"; // output: 2023-04-03 14:30:00 (example)
// Using DateTime object
$dateTime = new DateTime();
echo $dateTime->format('Y-m-d H:i:s') . "\n"; // output: identical
?>
Sample output reflects the date and time the code was run.
Deep Dive
Historically, PHP has evolved in handling date and time. Early PHP versions had fewer date manipulation features. The DateTime
class, introduced in PHP 5.2.0, provided object-oriented handling, timezone support, and more versatility.
Alternatives to date()
and DateTime
include:
strftime()
(locale-aware formatting)DateTimeImmutable
(immutable version ofDateTime
)- Extension classes like
Carbon
for more complex needs
Internally, both date()
and DateTime
rely on the server’s timezone settings unless otherwise specified. The DateTimeZone
class can manipulate timezones.