learn

DateTime and DateTimeZone classes

category: Advanced
Created by: Dr.Ferrous

DateTime and DateTimeZone classes

category: Advanced
Created by: Dr.Ferrous
twitter google+ facebook pinned 

Since version 5.2, PHP has provided a DateTime class that can handle much more date and time information at the same time, rather than working with separate date and time functions. Also, it works hand-in-hand with the new DateTimeZone class.

DateTime()

To use the DateTime class, and generally any class, you need to create an object of the class, with the new keyword.
Syntax:

This creates an instance of the DateTime class and stores it in a DateTime object called $now. The DateTime object is aware not only of the date and time it was created but also of the time zone used by the web server.

 

  • "time" argument is optional, it is a string with a valid literaly date/time format. If it is not added, PHP use current time.
  • "obj_timezone" is also optional, an object created with "new DateTimeZone()" representing the desired time zone (i.g new DateTimeZone('America/New_York')).
    When using the 'obj_timezone' parameter, enter NULL for "time" argument to obtain the current time.

Most classes have properties and methods, which are similar to variables and functions, they're related only to a particular instance of a class. For example, you can use the methods of the DateTime classs to change certain values, such as the month, year, or perform date calculations.


The object's properties and methods can be accessed using the "->" operator.

$object->property or $object->method()

 

The DateTime object uses only methods, here is some examples:

1) Get and output the current date/time and the day of the week of a specified date:

 

 

2) Set a new date and time for DateTime object and display it:

 

3) Get the Unix timestamp of a DateTime object:

 

4) Set the date and time based on an Unix timestamp.

setTimezone()

The setTimezone class can be used to reset /change the time zone of a DateTime object.
Example:

 

If you want to get the difference between two dates, you need to set a DateTime object for each one. Than, apply the diff() method (returns a DateIntervalobject representing the difference between the two dates).


Example, output the difference between the current time and "1996-07-07 14:45:00":