- The complete guide on working with dates and time in PHP
- How computers count time
- Unix Timestamp
- Standard Dates Reporting
- Setting and getting timezone on your server
- Timestamp function: time()
- PHP date() function
- Date function formatting options
- Conversion of date/time to Unix timestamp
- Converting a date into different formats
- Adding and subtracting days or time to a DateTime
- How to subtract 2 dates in PHP
- Comparison between 2 dates
- Conclusion
- Related Articles
- PHP Date and Time
- The PHP Date() Function
- Syntax
- Get a Date
- Example
- PHP Tip — Automatic Copyright Year
- Example
- Get a Time
- Example
- Get Your Time Zone
- Example
- Create a Date With mktime()
- Syntax
- Example
- Create a Date From a String With strtotime()
- Syntax
- Example
- Example
- More Date Examples
- Example
- Example
- Complete PHP Date Reference
The complete guide on working with dates and time in PHP
As a developer, nearly every application you will work on requires the use of time in some way. You will need to keep a record of the time in which various activities occur, such as the time in which a record is created, updated, deleted, when a user logs in, etc.
At some point, you’re going to have to collect, store, retrieve and display dates and times in different formats. You are also likely to do calculations involving time such as adding days to a day, subtracting a number of days from a date, comparing two days, etc.
In this article, we will cover in detail working with dates and times in PHP.
How computers count time
Computers count time from an instant called Unix epoch, which occurred on January 1, 1970, at 00:00:00 UTC(Coordinated Universal Time). UTC is also known as GMT(Greenwich Meridian Time), which is the time at a longitude of 0°.
Unix time elapses at the same rate as UTC. You can calculate the UTC date and time of any given instant since January 1, 1970, by counting the number of seconds since the Unix epoch, with the exception of leap seconds. Leap seconds are occasionally added to UTC to account for the slowing of the Earth’s rotation but are not added to Unix time.
Unix Timestamp
Unix timestamp is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC.
Standard Dates Reporting
Computers count time using Unix timestamp, calculating the number of seconds that have passed since Jan 1, 1970. However, this would be difficult and incredibly inefficient for humans. Thus, we work in terms of years, months, days, hours, minutes, and seconds.
But this also comes with complexities because different regions and cultures have different ways of writing the date. For instance, dates in the United States are written starting with the month, then day, then the year. December 31, 2021, will be written as 12-31-2021. On the other hand, the same date will be written as 31-12-2021 in Europe and other regions.
To standardize the date and help fix the communication mistakes, the International Organization for Standardization (ISO) introduced ISO8601. This standard specifies that all dates should be written in order of most-to-least-significant data. This means the format is the year, month, day, hour, minute, and second:
In the example above, YYYY represents a four-digit year, and MM and DD are the two-digit month and day, starting with a zero if less than 10. After that, HH, MM, and SS represent the two-digit hours, minutes, and seconds, starting with a zero if less than 10.
The above format eliminates the ambiguity in dates representation, where dates written as DD-MM-YYYY or MM-DD-YYYY can be misinterpreted if the day is a valid month number.
Most databases use YYYY-MM-DD HH:MM:SS format to store date and time and YYYY-MM-DD to store date.
Setting and getting timezone on your server
Different regions of the world have different timezones. You can know which timezone your web server is set to with the following PHP function.
To change to the timezone that will be used in your date and time functions in PHP, you do it with the function date_default_timezone_set($timezoneId), where $timezoneId is a string value.
The above code sets the timezone to that of Nairobi, Kenya. You can get a list of all timezones on this link
Unless all your website/app users are from the same region, it is always advisable to set your server time zone to UTC.
Below is how you set timezone to UTC in PHP:
For the date and time functions to pick and reflect the timezone specific time, you should always the function for setting the timezone at the top.
Timestamp function: time()
The function returns the current unix timestamp, ie. total number of seconds that have passed since January 1, 1970 at 00:00:00 UTC.
PHP date() function
The function returns a string formatted according to the given format string using the given integer timestamp.
It takes the format below:
Where $format is a string value and $timestamp an optional integer unix timestamp value.If $timestamp is not given, the function defaults to the value of time()
Date function formatting options
To convert/format a date in different formats using the date() function, you need to first convert that date into a Unix timestamp using the strtotime() function.
Conversion of date/time to Unix timestamp
The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Example 2: Displaying current time in DateTime format
Converting a date into different formats
You can convert the date into as many formats as possible by just manipulating various letters in the table above to form within the date() function, enclosed in single or double-quotes.
Adding and subtracting days or time to a DateTime
The easiest way to add or subtract time to/from date in PHP is by concatenating a string specifying the duration of time you want to add or subtract, to date, inside the strtotime() function, preceded with the plus (+) or minus (-) symbol.
Adding time to the current time
Adding time to a DateTime
Adding days, weeks, months and years to a date
How to subtract 2 dates in PHP
When you have two dates that you want to find their difference, PHP can help you find it.
You just convert the two dates to unix timestamps, subtract the two timestamps and find the difference between the two dates in seconds.
You then convert the time in seconds to the duration in which you want to measure the time in eg. hours, days, years, etc.
If you use DateTime format(date and time in the date), use the floor() function to round down and avoid decimals in time difference like below.
Comparison between 2 dates
It is quite easy to compare two dates and know which is older than the other.
If the two dates are exactly in the same format, you just compare them directly as below:
If the two dates have different formats, you will first need to convert the two to the Unix timestamp, then compare them as below.
Conclusion
Nearly in all applications, you will ever work on as a developer, in whatever language you decide to use, you will have to work with dates and time in one way or another.
In this article, we have covered working with dates in PHP. We have covered how computers count time, what Unix timestamp is, how to collect the current time, working with timezones, converting dates and time into multiple different formats, adding or subtracting time to or from a date, and dates comparison among other things.
Related Articles
PHP Date and Time
The PHP date() function is used to format a date and/or a time.
The PHP Date() Function
The PHP date() function formats a timestamp to a more readable date and time.
Syntax
Parameter | Description |
---|---|
format | Required. Specifies the format of the timestamp |
timestamp | Optional. Specifies a timestamp. Default is the current date and time |
A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.
Get a Date
The required format parameter of the date() function specifies how to format the date (or time).
Here are some characters that are commonly used for dates:
- d — Represents the day of the month (01 to 31)
- m — Represents a month (01 to 12)
- Y — Represents a year (in four digits)
- l (lowercase ‘L’) — Represents the day of the week
Other characters, like»/», «.», or «-» can also be inserted between the characters to add additional formatting.
The example below formats today’s date in three different ways:
Example
echo «Today is » . date(«Y/m/d») . «
«;
echo «Today is » . date(«Y.m.d») . «
«;
echo «Today is » . date(«Y-m-d») . «
«;
echo «Today is » . date(«l»);
?>?php
PHP Tip — Automatic Copyright Year
Use the date() function to automatically update the copyright year on your website:
Example
Get a Time
Here are some characters that are commonly used for times:
- H — 24-hour format of an hour (00 to 23)
- h — 12-hour format of an hour with leading zeros (01 to 12)
- i — Minutes with leading zeros (00 to 59)
- s — Seconds with leading zeros (00 to 59)
- a — Lowercase Ante meridiem and Post meridiem (am or pm)
The example below outputs the current time in the specified format:
Example
Note that the PHP date() function will return the current date/time of the server!
Get Your Time Zone
If the time you got back from the code is not correct, it’s probably because your server is in another country or set up for a different timezone.
So, if you need the time to be correct according to a specific location, you can set the timezone you want to use.
The example below sets the timezone to «America/New_York», then outputs the current time in the specified format:
Example
Create a Date With mktime()
The optional timestamp parameter in the date() function specifies a timestamp. If omitted, the current date and time will be used (as in the examples above).
The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.
Syntax
The example below creates a date and time with the date() function from a number of parameters in the mktime() function:
Example
Create a Date From a String With strtotime()
The PHP strtotime() function is used to convert a human readable date string into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT).
Syntax
The example below creates a date and time from the strtotime() function:
Example
PHP is quite clever about converting a string to a date, so you can put in various values:
Example
$d=strtotime(«next Saturday»);
echo date(«Y-m-d h:i:sa», $d) . «
«;
However, strtotime() is not perfect, so remember to check the strings you put in there.
More Date Examples
The example below outputs the dates for the next six Saturdays:
Example
$startdate = strtotime(«Saturday»);
$enddate = strtotime(«+6 weeks», $startdate);
?php
while ($startdate < $enddate) echo date("M d", $startdate) . "
«;
$startdate = strtotime(«+1 week», $startdate);
>
?>
The example below outputs the number of days until 4th of July:
Example
$d1=strtotime(«July 04»);
$d2=ceil(($d1-time())/60/60/24);
echo «There are » . $d2 .» days until 4th of July.»;
?>?php
Complete PHP Date Reference
For a complete reference of all date functions, go to our complete PHP Date Reference.
The reference contains a brief description, and examples of use, for each function!