The strtotime() function in PHP allows you to convert English text date time strings into UNIX timestamps. It is useful for converting database datetime strings into UNIX timestamps and also creating dates into the future or past based on the current time or relative to a date and time in the future or the past. This post looks at some examples of doing this.
The PHP function strtotime() has the following usage:
This means that you pass in a string value for the time, and optionally a value for the current time, which is a UNIX timestamp. The value that is returned is an integer which is a UNIX timestamp.
An example of this usage is as follows, where the date passed to strtotime() might be a date from a database query or similar:
This will return into the $ts variable the value 1198148400, which is the UNIX timestamp for the date December 21st 2007. This can be confirmed using the date() function like so:
strtotime() is able to parse a wide variety of strings and convert them to the appropriate timestamp, using actual dates and also strings such as "next week", "next tuesday", "last thursday", "2 weeks ago" and so on. Here are some examples:
This will display the following:
If today is December 21st, then the following:
will display the following:
Using strtotime to offset from a different date
If you want to use the PHP function strtotime to add or subtract a number of days, weeks, months or years from a date other than the current time, you can do it by passing the second optional parameter to the strtotime() function, or by adding it into the string which defines the time to parse.
This example shows passing the second parameter. Doing it this way requires that the date to offset from is already a UNIX timestamp. In this example the timestamp being passed is December 25th 2007 (Christmas Day).
The result would be:
As you can see, 'tomorrow' has been parsed as tomorrow starting from the 1198494000 timestamp, which is December 25th 2007, resulting in a timestamp being returned as December 26th 2007.
Another way to add or subtract time from an existing time string is to add it into the datetime string like so, where we are adding 90 days on to a date value, in the format of the MySQL date field:
This would output:
As you can see the strtotime() function is extremely useful for parsing English (and databases) representations of date and time strings and turning them into UNIX timestamps. It is also useful for adding plus and minus offsets to those timestamps to easily create dates and times in the future and past.
0 comments:
Post a Comment