PHP offers a few really nice functions to manipulate dates and times. With the functions built into PHP, you can easily pull individual parts of a date or time and use it or format it just about any way you want.
To start, you should really familiarize yourself with PHP’s
strtotime() function. The
strtotime() function takes a standard date (and optional time) and converts it into a Unix timestamp. Because the
strtotime() function returns boolean
false if it doesn’t recognize the input as a valid date/time, you can also use it to check the validity of a date.
This can be especially helpful when retrieving dates and times from an SQL database, as most database management systems (DBMS) store timestamps in a standard, readable date format (YYYY-MM-DD HH:MM:SS). With the strtotime() function, you can convert the SQL timestamp into a unix timestamp to compare it with timestamps natively generated by PHP.
time() function simply retrieves the current time (as established by the server) as a unix timestamp. Since it returns a unix timestamp, it obviously doesn’t do you a great deal of good without utilizing other functions to format that timestamp into a standard date/time format, but it is a necessary function when attempting to mark when certain events occurred on your server.
date() function is the main function you’ll probably use when manipulating dates and times in PHP. The
date() function accepts a string indicating the desired output format, along with an optional unix timestamp (if left out, the
date() function will use the current timestamp).
The format options are extremely versatile, allowing you to format the year, month, day, hours, minutes, seconds and more. You can even use the date() function to output an ISO-8601 or RFC 2822 date (for use with things such as RSS feeds, HTTP headers, etc.).
Other Date/Time Functions
Some other functions you may find helpful include:
mktime()– returns a unix timestamp based on a comma separated list of date/time parts (hour, minute, second, month, day, year, daylight saving time)
strftime()– similar to the
date()function, except that it adjusts the format of the date based on the current locale settings
getdate()– returns an associative array of date parts