You’ll master PHP’s flexible calendar methods in no time at all!
When working on PHP code that calls for date and time manipulation, especially forums, discussion boards and blogs where date and time functions are important, you’ll regularly encounter situations where you need to display different formats or styles of date and time.
PHP includes a range of functions which can help you to easily format and adjust your date and time displays to suit your needs. In this tutorial, we’ll look at some easy ways to display calendar information for your visitors.
One of the simplest date/time functions in PHP is time().
This simple function takes no arguments, and simply returns a numeric value equal to the number of seconds since the “Unix Epoch”, declared as January 1st 1970 at midnight (GMT) – just an arbitrary date chosen to base timing calculations on when working with dates and times.
This gives a start time upon which we can base our time calculations
$time = time();
echo $time; //gives us something like 1219075172
It’s really useful to get a numerical representation of the timestamp, but it’ll be far handier for us to convert PHP DateTime to string representation.
This timestamp can then be used as input to the date() function to format it for improved readability – we’ll be taking this very human-unfriendly number and passing it through a method in PHP DateTime to string.
The date() function takes, as its arguments, a string to define how we wish the formatted time to appear and secondly, a Unix timestamp just like the one returned by time().
It is also possible to use date() without specifying a timestamp and it will use the current time as its source.
Here’s an example of using PHP DateTime to string functionality:
echo date("F j, Y, g:i a", 1219075172); //produces "August 18, 2008, 4:59 pm"
The string used in the date() function can contain a number of single letters which are then substituted for their human readable counterparts according to the value of the timestamp. In our case, the following substitutions are made
An alternative to the time() function is mktime(). This function is useful when we wish to use a date/time which is not the current time. mktime() takes as its arguments numerical values representing, in this order – hours, minutes, seconds, months, days, years – and a final value to declare whether daylight savings time is to be taken into account.
$date = mktime(10, 15, 0, 12, 12, 1980); //produces 345464100
echo date("F j, Y, g:i a", $date); //produces "December 12, 1980, 10:15 am"
The PHP function microtime() returns a similar value to time(), but returns a more accurate floating-point representation of the number of seconds since the Unix Epoch.
It is not usually used in the same way as the previous time functions, but is used more often when debugging PHP code and analysing the time of execution of functions for performance enhancement purposes microtime() only takes one argument, and that is a boolean value stating whether or not to return the value as a floating point number rather than a formatted string.
Using microtime() without this parameter can produce some confusing results if you’re not aware of its behaviour. Notice here how the first call returns the time as a string split into microseconds and seconds
echo microtime(); // produces 0.61273200 1219075923
echo microtime(true); // produces 1219075923.6128
If you try using the value of the first function call directly, PHP will treat it as a string, and give inaccurate results.
Here is an example of using microtime() to measure the performance of a for-loop compared with a while-loop performing 10 million repetitions of a single increment operation. Before each loop, we record the start time using microtime(), and compare it to the end time after each loop is complete.
$while_start = microtime(true);
$count = 0;
while($count < 10000000){
$count++;
}
$duration_while = (microtime(true)-$while_start)*1000;
printf ("While loop execution in %.3f ms", $duration_while);
$for_start = microtime(true);
$count = 0;
for($i=0; $i<10000000; $i++){
$count++;
}
$duration_for = (microtime(true)-$for_start)*1000;
printf ("For loop execution in %.3f ms", $duration_for);
This code produces the following result (based upon execution times on my system)
While loop execution in 787.590 ms
For loop execution in 1363.392 ms
We also multiply the values on lines 6 and 13 to get a value in microseconds, rather than seconds
Sometimes you’ll find it useful to be able to tell a PHP in plain language exactly what time you want to send to the date() function.
Just like above when we were performing PHP DateTime to string, we’ll be running a similar method but also passing in the relative date using plain English!
The strtotime() function can do just that. It will take as an input an English-language string describing a date and convert it into a Unix timestamp which can then be passed into the date() funtion. It will take an optional second value of another Unix timestamp from which to calculate the result. For example (this code was generated on Monday, 18th August, 2008)
echo date("jS F, Y", strtotime("next friday")); //22nd August, 2008
echo date("jS F, Y", strtotime("last tuesday")); //12th August, 2008
echo date("jS F, Y", strtotime("3 years, 2 months, 1 day")); //19th October, 2011
echo date("jS F, Y", strtotime("5 weeks ago")); //14th July, 2008
The strtotime() function will pick up on most English language date descriptions you give it, but it’s not perfect! For a full description of the strings you can pass to it, check out the GNU Date input formats
Robin is the dedicated developer behind Solarise.dev. With years of experience in web development, he's committed to delivering high-quality solutions and ensuring websites run smoothly. Always eager to learn and adapt to the ever-changing digital landscape, Robin believes in the power of collaboration and sharing knowledge. Outside of coding, he enjoys diving into tech news and exploring new tools in the industry.
If you'd like to get in touch to discuss a project, or if you'd just like to ask a question, fill in the form below.
Send me a message and I'll get back to you as soon as possible. Ask me about anything - web development, project proposals or just say hi!