Open In App

How to use the Date and Time in PHP ?

Date and time handling in PHP is crucial for various web applications, ranging from simple date displays to complex calculations involving time zones and intervals.

PHP provides a rich set of functions and classes to manage dates and times efficiently. Understanding these functionalities enables developers to perform tasks like date formatting, parsing, arithmetic, and time zone conversions effectively.



Approach

Getting the current date and time

It retrieves the current date and time in the specified formats using PHP’s date() function and DateTime object.

$currentDate = date('Y-m-d');  //  [date] => 2024-02-12 11:39:49.272639
$currentTime = date('H:i:s'); // [timezone_type] => 3
$dateTime = new DateTime( ); // [timezone] => UTC

Formatting dates

It formats a given date (‘2024-02-11’) into a human-readable format (‘February 11, 2024’) using strtotime() and DateTime::format().



$formattedDate = date('F j, Y', strtotime('2024-02-11'));   // February 11, 2024
$formattedDateTime = $dateTime->format('Y-m-d H:i:s'); // 2024-02-12 11:43:38

Manipulating dates

It calculates the date for the next week, modifies the current date to the next day, and formats them accordingly using strtotime(), date(), and DateTime::modify().

$nextWeek = strtotime('+1 week');
$newDate = date('Y-m-d', $nextWeek);
$dateTime->modify('+1 day');
$modifiedDate = $dateTime->format('Y-m-d');

Parsing dates

It converts a string date (‘2024-02-11’) into a human-readable format (‘February 11, 2024’) using strtotime() and date(). Additionally, creates a DateTime object from a string date and time (‘2024-02-11 15:30:00’) using DateTime::createFromFormat().

$timestamp = strtotime('2024-02-11');
$parsedDate = date('F j, Y', $timestamp);
$parsedDateTime = DateTime::createFromFormat('Y-m-d H:i:s', '2024-02-11 15:30:00');

//output
DateTime Object
(
[date] => 2024-02-11 15:30:00.000000
[timezone_type] => 3
[timezone] => UTC
)

Each letter in the format string represents a part of the date and time:

Article Tags :