The date() function in PHP is powerful and complex. In this article, we’ll teach you how to get started.
PHP is an amazing language. Powerful enough to be at the core of the biggest blogging platform (WordPress), deep enough to run the largest social network (Facebook) yet easy enough to be a beginner’s first server side language. It’s available in even the cheapest shared hosting services and with tools like WAMP and MAMP, it’s easy to install on a local machine. The language has rich libraries of pre-built functions that make it easy for developers to get things done. A great place to get started is the rich ‘date’ functions since working with dates is at the core of many projects.
PHP is a server side language, which means that unlike regular HTML, you can’t preview it in your machine’s browser by default unless you use a solution like WAMP or MAMP to run a a copy of the services on your machine. Before you preview these example on a browser, make sure you’ve set up a good testing environment.
PHP code is often embedded onto an existing HTML page which is almost always saved with a .php extension. The .php extension tells the server that it needs to process the php in the file before it sends it to the client. The client won’t see any of the PHP code, they see the results of the processed code.
Getting a simple date
We’re going to use the echo command to output something to our client’s browser…in this case, the date. We’ll do this in a basic page with the following code.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Getting started with dates in php5</title> </head> <body> <?php echo "Today is ",date('l'); ?> </body> </html>
If you’ve set things up correctly, you should see something like this on your browser:
Today is Sunday
The function outputs the text for the name of the day of the week. The date function takes at least one parameter…a string that tells the function how to format the current date.
Trying out different formats
If you look at the manual for the PHP date function, you’ll see that there are many ways to format dates. So, to get a date that would work as input for a MySQL database, you might use.
<?php echo "Today is ",date('Y-m-d'); ?>
Today is 2011-06-26
There are some dates that are so common so there’s a few constants you can use. For example to get a date for your cookies you can use:
<?php echo "Today is ",date(DATE_COOKIE); ?>
Which gives you something like:
Today is Sunday, 26-Jun-11 16:26:22 EDT
Note that the quotes are gone when using constants.
What about time?
If you want to output the current time, you can use
date() with a different formatting string.
<?php echo "The time is ",date('g:i:sa'); ?>
The time is 6:06:25pm
Localizing your time zone
If you notice that the time you got back from the code above is not the right time, then more than likely, it’s due to a the fact that your server is set up for a different timezone. If you need the time to correlate to a specific location, then you can use something like this:
<?php date_default_timezone_set('America/New_York'); echo "The time is ",date('g:i:sa'); ?>
This will set the time to Eastern Standard Time in the US. This is a
PHP5 function (so be careful with older versions of PHP) and there are a number of strings you can use here to convert the time to your local timezone. If you need this on a more permanent basis, you should probably change your php.ini file.
Getting other dates
Often, you’ll need to do something with a date other than the current date. When you create a date with the
date() function, the system uses the Unix system time, which is calculated as the number of seconds from January 1 1970 00:00:00 GMT, otherwise known as the Unix Epoch time.
To specify that the date function return something other than the current date, you can simply feed it the number of seconds since that date as the second parameter to the function:
<?php echo "Today is ",date('Y-m-d', 1309133434); ?>
Which results in:
Today is 2011-06-26
That doesn’t seem particularly useful, but it means that you can use the date functions to do calculations. But before you do that, you need an easier way to creating dates.
There’s a couple of ways to do that. We can use the
mktime() function to create times from a number of parameters we feed this function.
<?php $mytime=mktime(9, 23, 33, 6, 26, 2011); echo "Today is ",date('Y-m-d g:i:sa', $mytime); ?>
This results in the following:
Today is 2011-06-26 9:23:33am
You can tell from the example that the parameters you pass stand for the hour, minute, seconds, month, day and year you want to create. This is a good way of creating dates but there’s an even cooler way to do it.
Getting a date from a string
You can use the
strtotime() function to have php convert a human readable string to a Unix time. PHP is quite smart about converting this string to a date so you can plug in a variety of values. Here’s an easy example:
<?php $mytime=strtotime("7:50pm June 26 2011"); echo "Today is ",date('Y-m-d g:i:sa', $mytime); ?>
Today is 2011-06-26 7:50:00pm
PHP is quite clever about interpreting the string, but it’s not perfect, so make sure you test the string you put in there. This is a great way to convert MySQL or other types of strings let’s you use english-like instructions. So you can do things like:
$nextfriday=strtotime("next Friday"); //next friday $nextmonth=strtotime("+1 Month"); //On month from today $lastchristmas=strtotime("-1 year dec 25"); //last christmas
Getting a date range
strtotime returns are converted to numbers that can be compared with simple arithmetic, so you can do interesting things with them. Let’s say, for example, that you’re teaching a class for the next 16 weeks starting next Tuesday. You’re not sure when 16 weeks from now is, plus, you’d like to get the date of each of your classes so you can start preparing your curriculum. You can do something like this.
<?php $startdate=strtotime("next Tuesday"); $enddate=strtotime("+16 weeks",$startdate); //16 weeks from the starting date $currentdate=$startdate; echo "<ol>"; while ($currentdate < $enddate): //loop through the dates echo "t<li>",date('M d', $currentdate),"</li>"; $currentdate = strtotime("+1 week", $currentdate); //increment the current date endwhile; // calculate date range echo "<ol>"; ?>
This will show something like this:
1. Jun 28 2. Jul 05 3. Jul 12 4. Jul 19 5. Jul 26 6. Aug 02 7. Aug 09 8. Aug 16 9. Aug 23 10. Aug 30 11. Sep 06 12. Sep 13 13. Sep 20 14. Sep 27 15. Oct 04 16. Oct 11
Notice this line
$currentdate = strtotime("+1 week", $currentdate). On this line, you can see that
strtotime can if you specify a date number as the second parameter,
strtotime will use than instead of the default (today) for it’s calculations.
Days until a certain date
When working on a calendar, a common calculation is to find out the amount of days until a certain date. You can easily calculate the days until next thanksgiving in the US, which is on the fourth thursday in November.
<?php $someday=strtotime("3 weeks thursday November 1"); $daysuntildate=ceil(($someday-time())/60/60/24); echo "There are ",$daysuntildate," until Thanksgiving"; ?>
First, we started by calculating the thanksgiving date which was 3 weeks after the first thursday from November 1st (or the same thing as the fourth thursday). Then we used some simple arithmetic to calculate the difference between that date and the current time. When we do a comparison, we use the
time() function because it gives us the current date in seconds from the Unix Epoch date.
That number is the number of seconds between those two dates. We do a simple calculation to divide that number by the minutes/hours/days (60/60/14) and we get the number of days between the two numbers. We need to use the ceil function which rounds any fractions we’re left over after our calculation.
Having fun with dates
If you’re just getting started with PHP, working with dates is a great way to get the feel of the language. There’s quite a lot of fun things you can do. Dig around the Date and Time related functions in the PHP manual and share what you can do.
Comments are closed.