February 2, 2012 learn_php

Handling dates in PHP

Handling dates in PHP

Dates in php are often overlooked and people tend to think that they will not need to handle dates, but indeed my friend, you will need to know how to handle dates when working with PHP. The most common function in PHP to retrieve the date is date(). This function takes two parameters, one of them which is optional. The first parameter is a string, which will indicate to the function, the format that you would like to recieve the date. If you wanted to grab today’s date, then it would be simply like this:

This would produce something like: 1st February 2012. For a full list of date formats, you can find them here in the PHP.net manual. http://www.php.net/manual/en/function.date.php

For the second parameter of this date function is the Unix timestamp. What is it exactly? Unix has a particular way of storing the current time and the date. It stores a 32-bit integer that has the number of seconds from midnight of January 1st, 1970. Since this timestamp only uses a 32 bit int, then you will most likely encounter problems when dealing with dates greater than the year of 2038, and less than the year 1970. Make sure you think about this aspect when implementing any date processing in your script.

There is another function in PHP, that can be used to create a unix timestamp. To do this, you would use the function: mktime(). This function used to take seven parameters, but as of PHP version 5.1.0, the last parameter has been deprecated. I will give them in order:

The last parameter (is_dst) refers to, ‘Is daylight savings time?’.

So, to create a unix timestamp, can be done in the following three ways. “All are different functions that give the same result”.

The recommended function to use to get the timestamp is time(). This is due to an update made in PHP 5.1.0, that if mktime() is called without any arguments it will throw an E_STRICT notice.

Another useful date function is the getdate(). This function takes one parameter, and it’s optional. The parameter to pass to it is the unix timestamp. If no timestamp is passed to it, then this function will technically be the same as time(), in the sense that it will return the current date and time. The result will be an array with the following:

How to validate a date

When creating a web application, at some point you will need to validate the users date input. You do not want a user inputting an invalid date, or might just cause you problems when either calculating them, or even storing them. Here’s how:

This previous function will return true or false depending on the values passed on to it.

Calculate a date

It is possible to calculate a timeframe between 2 dates. You can also calculate what will the date be from here to two months ahead. Let’s calculate what will be the date within 2 months of today. Steps are as follows:

There you have it. Another way to achieve this is that you can add days to the current day. The logic behind this is simple, the function will automatically calculate if there are more days than what any given month can handle. If we were to add the days, let’s say 90 days from now, we would say something like this:

Let’s take today for example, it is February 2, 2012. The arithmetic operation that will take place is 2 + 90 which will equal 92. Obviously this is not a valid number date in any month, so the function will just calculate the date for you, returning an exact date. Also, I have added ’12’ in the first parameter, to get rid of some problems you might get when calculating days with daylight savings time. If in the process it encounters a daylight savings time, then the resulting time will not be 12, it could probably be 13, or 11 depending on the dates, thus returning you the date you want.

Calculate an age

An example of how to calculate dates between 2 dates are as follows:

You need to remember that this previous example is limited to the unix timestamp, and will only be able to calculate dates down to 1970. Afterwards, I will have examples of dates with MySQL. I hope you liked it.

4 thoughts on “Handling dates in PHP

  1. I just want to add that using DateTime (http://ca2.php.net/manual/en/datetime.construct.php) can be even more useful because it can optionally accept a DateTimeZone parameter(when you have to build a website targeting nationwide audience, it’s a lifesaver).
    IMHO I think it’s also easier to use. Calculating the difference (http://ca2.php.net/manual/en/datetime.diff.php) between 2 object and modifying a DateTime is very straightforward (http://ca2.php.net/manual/en/datetime.modify.php).

    Just my 2 pennies 🙂

  2. I’m surprised that strtotime() was not mentioned in this article. Considering the myriad different date formats in the current global economic space I have found strtotime() to be invaluable in getting a valid timestamp from almost any format someone might use in a date.

    1. Hey Jeff,

      I have to say you are right, but I have a small continuation for this post which will mention an example of how to use strtotime(). What I need to do is hurry up and post it, but again I have been bombarded at work with so much to do, that it leaves me no time. Soon though, I will have the continuation for this post. 😀

  3. hola estoy siguiendo tu ejemplo pero la verdad no logro como evitar que se exceda a una fecha incorrecta por ejmplo 110 dias o mes 13. podrias dar mas explicacion de como evita esto la funcion

Leave a Reply

Your email address will not be published. Required fields are marked *

The qTranslate Editor has disabled itself because it hasn't been tested with your Wordpress version yet. This is done to prevent Wordpress from malfunctioning. You can reenable it by clicking here (may cause data loss! Use at own risk!). To remove this message permanently, please update qTranslate to the corresponding version.