Categories
PHP

The DateTime Class

The DateTime class deals with a wide range of date and time calculations, it provides an object-oriented interface to accurately create and manipulate dates and times.

To create a new DateTime object, instantiate an object and store it in a variable. Without arguments, the DateTime class constructor creates an instance that represents the current date and time:

<?php
 # Current date and time
 $date = new DateTime();
 echo $date->format('d M Y, H:i:s');
 # 13 Aug 2022, 05:21:33

Similar to date() function, the DateTime::format() method also uses the formatting characters to format the date and time string. PHP also provide several predefined date constants that may be used instead:

<?php
 $date = new DateTime('August 13, 2022 4:52:01 PM');
 //Using predefined date constant
 echo $date->format(DATE_ATOM);
 # 2022-08-13T16:52:01+02:00

Similar to strtotime() function, the DateTime class understands a wide range of string formats (see, converting string to date and time.). In the following example, we passed a string argument into the DateTime class constructor with the custom date and time format:

<?php
 $date = new DateTime('5PM 1st August 2017');
 echo $date->format('d M Y, H:i:s') . '<br>';
 # 01 Aug 2017, 17:00:00

 $date = new DateTime('Yesterday');
 echo $date->format('d M Y, H:i:s') . '<br>';
 # 12 Aug 2022, 00:00:00

 $date = new DateTime('Tomorrow');
 echo $date->format(DATE_ATOM);
 # 2022-08-15T00:00:00+02:00

You can also get the date and time of a specific time zone by providing the DateTimeZone class instance in the second argument of DateTime object, see how to represent times in different parts of the world.

Note: The DateTimeImmutable Class

When working with date and time, it is recommended to use DateTimeImmutable class instead of the DateTime class. It works the same as the DateTime, except that their property values cannot be altered. For more information visit the DateTime documentation page.

Example: DateTime::createFromFormat

Sometimes you must work with date and time values in different and unexpected formats. In that situation, you can use the DateTime::createFromFormat() static method, its first argument is the date and time string format and the second argument is the date and time string that uses the format mentioned in the first argument:

<?php
 $date = DateTime::createFromFormat(
         'F d, Y g:i:s A', 'August 13, 2022 4:52:01 PM'
         );
 echo $date->format('D, d M Y, H:i:s');
 # Sat, 13 Aug 2022, 16:52:01

The DateTime::createFromFormat() method accepts the same date and time formats as the date() function. You can also use the date_parse_from_format() function which returns an associative array of date and time information.

Example: DateTime:: modify

The DateTime::modify() method modifies the date and time stored in the object. It accepts a string in a format accepted by strtotime() function, for example ‘+10 days’ or ‘+10 months’, etc.

<?php
 $date = new DateTime('August 13, 2022 4:52 PM');
 $date->modify ('+10 days');
 echo $date->format('d M Y, H:i:s') . '<br>';
 # 23 Aug 2022, 16:52:00
 
 $date->modify ('+10 months');
 echo $date->format('d M Y, H:i:s');
 # 23 Jun 2023, 16:52:00

Example: DateTime::setTime()

The DateTime::setTime($hour, $minute, $second) method resets the time stored by the object. The $second argument is optional (returns 00 if not provided).

<?php
 $date = new DateTime('August 13, 2022 4:52 PM');
 $date->setTime(23,59,59);
 echo $date->format('d M Y, H:i:s');
 # 13 Aug 2022, 23:59:59

Example: DateTime::SetDate()

The DateTime::setDate($year, $month, $date) method resets the date stored by the object.

<?php
 $date = new DateTime('August 13, 2022 4:52 PM');
 $date->setDate(2000,12,31);
 echo $date->format('d M Y, H:i:s');
 # 31 Dec 2000, 16:52:00

Example: DateTime::SetISODate()

The DateTime::setISODate($year, $week, $weekDay) method is a specialized way of representing the date using the “week date” format of ISO 8601, for more information visit http://wikipedia.org/wiki/ISO_8601.

  • $year is the calendar year,
  • $week is the week number,
  • $weekDay is a number from 0 to 6 (optional, default value is 1). “0 = Sunday”, “1 = Monday”, “2 = Tuesday”…, “6 = Saturday”.
<?php
 $date = new DateTime('August 13, 2022 4:52 PM');
 //First week, default day value is 1 (Monday)
 $date->setISODate(2022,1);
 echo $date->format('D, d M Y, H:i:s') . '<br>';
 # Mon, 03 Jan 2022, 16:52:00
 
 //Second week, day value is 4 (Thursday)
 $date->setISODate(2022,2,4);
 echo $date->format('D, d M Y, H:i:s');
 # Thu, 13 Jan 2022, 16:52:00

Example: DateTime::getTimestamp()

You can use the DateTime::getTimestamp() method to retrieve Unix timestamp for the current or given date and time:

<?php
 #Get timestamp for the current dateTime
 $date = new DateTime();
 echo $date->getTimestamp(); # 1660458419

 #Get timestamp for the specific dateTime
 $date = new DateTime('August 13, 2022 4:52 PM');
 echo $date->getTimestamp(); # 1660402320

You can also use the other PHP’s function to generate a Unix timestamp.

Example: DateTime::setTimestamp()

You can use the DateTime::setTimestamp() method to convert a timestamp to date and time :

<?php
 $date = new DateTime();
 $date->setTimestamp(1660002320);
 echo $date->format(DateTime::RSS);
 #Tue, 09 Aug 2022 01:45:20 +0200

Example: DateTime::diff()

This method calculates the difference between two DateTime objects, it returns DateInterval object. You can format the DateInterval object with the DateInterval::format() method that provides formatting characters to format the interval:

<?php
 $date1 = new DateTime('2020-12-24');
 $date2 = new DateTime('2022-08-22');
 $interval = $date1->diff($date2);
 echo $interval->format('Years: %y, months: %m, and days: %d');
 # Prints: Years: 1, months: 7, and days: 29

The Date and Time Tutorials: