- Display time with php
- 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
Display time with php
- Different ways to write a PHP code
- How to write comments in PHP ?
- Introduction to Codeignitor (PHP)
- How to echo HTML in PHP ?
- Error handling in PHP
- How to show All Errors in PHP ?
- How to Start and Stop a Timer in PHP ?
- How to create default function parameter in PHP?
- How to check if mod_rewrite is enabled in PHP ?
- Web Scraping in PHP Using Simple HTML DOM Parser
- How to pass form variables from one page to other page in PHP ?
- How to display logged in user information in PHP ?
- How to find out where a function is defined using PHP ?
- How to Get $_POST from multiple check-boxes ?
- How to Secure hash and salt for PHP passwords ?
- Program to Insert new item in array on any position in PHP
- PHP append one array to another
- How to delete an Element From an Array in PHP ?
- How to print all the values of an array in PHP ?
- How to perform Array Delete by Value Not Key in PHP ?
- Removing Array Element and Re-Indexing in PHP
- How to count all array elements in PHP ?
- How to insert an item at the beginning of an array in PHP ?
- PHP Check if two arrays contain same elements
- Merge two arrays keeping original keys in PHP
- PHP program to find the maximum and the minimum in array
- How to check a key exists in an array in PHP ?
- PHP | Second most frequent element in an array
- Sort array of objects by object fields in PHP
- PHP | Sort array of strings in natural and standard orders
- How to pass PHP Variables by reference ?
- How to format Phone Numbers in PHP ?
- How to use php serialize() and unserialize() Function
- Implementing callback in PHP
- PHP | Merging two or more arrays using array_merge()
- PHP program to print an arithmetic progression series using inbuilt functions
- How to prevent SQL Injection in PHP ?
- How to extract the user name from the email ID using PHP ?
- How to count rows in MySQL table in PHP ?
- How to parse a CSV File in PHP ?
- How to generate simple random password from a given string using PHP ?
- How to upload images in MySQL using PHP PDO ?
- How to check foreach Loop Key Value in PHP ?
- How to properly Format a Number With Leading Zeros in PHP ?
- How to get a File Extension in PHP ?
- How to get the current Date and Time in PHP ?
- PHP program to change date format
- How to convert DateTime to String using PHP ?
- How to get Time Difference in Minutes in PHP ?
- Return all dates between two dates in an array in PHP
- Sort an array of dates in PHP
- How to get the time of the last modification of the current page in PHP?
- How to convert a Date into Timestamp using PHP ?
- How to add 24 hours to a unix timestamp in php?
- Sort a multidimensional array by date element in PHP
- Convert timestamp to readable date/time in PHP
- PHP | Number of week days between two dates
- PHP | Converting string to Date and DateTime
- How to get last day of a month from date in PHP ?
- PHP | Change strings in an array to uppercase
- How to convert first character of all the words uppercase using PHP ?
- How to get the last character of a string in PHP ?
- How to convert uppercase string to lowercase using PHP ?
- How to extract Numbers From a String in PHP ?
- How to replace String in PHP ?
- How to Encrypt and Decrypt a PHP String ?
- How to display string values within a table using PHP ?
- How to write Multi-Line Strings in PHP ?
- How to check if a String Contains a Substring in PHP ?
- How to append a string in PHP ?
- How to remove white spaces only beginning/end of a string using PHP ?
- How to Remove Special Character from String in PHP ?
- How to create a string by joining the array elements using PHP ?
- How to prepend a string in PHP ?
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.