In PHP5.2, the DateTime and DateTimeZone classes have appeared for working with date / time. At first, I didn’t pay attention to them, because I was used to using date (), etc. functions. But then I decided to still see what opportunities new classes are implementing.
Datetime
Class constructor
DateTime DateTime :: __ construct ([string $ time [, DateTimeZone $ timezone]])
The constructor takes two parameters:
1. A string in the format accepted by
strtotime () , by default - “now”.
2. The zone for which we will consider time.
Format method
string DateTime :: format (string $ format)
Returns the date according to the specified format.
Same as
date () function
Modify method
void DateTime :: modify (string $ modify)
Function to change the current time.
Takes one parameter - a string in the format accepted by
strtotime ()For example, you need to get a date that will be in a week:
$ date = new DateTime ();
echo $ date-> format ("Ymd"); // 2008-07-16
$ date-> modify ('+1 week');
echo $ date-> format ("Ymd"); // 2008-07-23
A php4 implementation would be like this:
echo date ('Ymd'); // 2008-07-16
echo date ('Ym-d', time () + (7 * 24 * 3600)); // 2008-07-23
Agree, more convenient ...
')
GetOffset method
int DateTime :: getOffset (void)
Returns the difference in seconds between UTC and the current time zone.
$ tz = new DateTimeZone ("Etc / GMT + 2");
$ time = new DateTime ();
$ time-> setTimezone ($ tz);
echo $ time-> getOffset (); // 7200
GetTimezone method
DateTimeZone DateTime :: getTimezone (void)
Returns a DateTimeZone related to DateTime, or false if unsuccessful
SetTimezone method
void DateTime :: setTimezone (DateTimeZone $ timezone)
Set DateTimeZone
SetTime method
void DateTime :: setTime (int $ hour, int $ minute [, int $ second])
Set the current time
SetDate method
void DateTime :: setDate (int $ year, int $ month, int $ day)
Set the current date
SetISODate method
void DateTime :: setISODate (int $ year, int $ week [, int $ day])
Set the current iso date
Instead of conclusion
My opinion DateTime class in the form in which it is now, does not make life much easier for developers,
but it can serve as a good springboard for writing child classes for specific needs.
As for the choice of what to use - this is an individual case of the developer.
PS: I hope this topic was useful ...