Visit the Official PHP Website
By James N Hitz
The date() function
The date() function returns a string formatted according to a given format specification using the given time. If not time is supplied, the current system time is used. The usage of date() is:
$formatedDate = ("format specification", time to format)
If the second argument ("time to format") is not specified, the current system date is used. The first argument ("format specification") is specified using special characters. The following characters are recognized in the format string:
Unrecognized characters in the format string will be printed as they are.
Check out the following examples:
print (date ("l dS of F Y h:i:s A")); print "<p>"; print ("July 1, 2000 was on a " . date ("l", mktime(0,0,0,7,1,2000)));
On execution the code above produced something like this on my computer:
Tuesday 15th of May 2001 05:46:15 PM
Ok. Let's try and clear the air starting with thte first example. We specify l (lowercase l) - Refering to the above table we see lowercase l gives the day of the week in full hence Tuesday. d gives the date and S gives the date suffix hence 15 and th --> 15th. F gives the full month, Y the year.... the rest is obvious. Just refer to the table above. Since ONLY ONE argument is not specified the Current System Date is used. Happended to be 15th May 2001 on my computer.
The second example on the other hand has both arguments. The format string supplied is only one -> l that causes the day of the week to be displayed. The other part is the one that supplies the date to be formatted. This is provided using the mktime() function discussed in the other page. As you can see the hour, minute and second are all set to zero (0) and the month, date and year are supplied IN THAT ORDER as is expected by the mktime() function.
It is possible to use date() and mktime() together to find dates in the future or the past.
$tomorrow = mktime (0,0,0,date("m"), date("d")+1,date("Y")); $lastmonth = mktime (0,0,0,date("m") -1, date("d"), date("Y")); $nextyear = mktime (0,0,0,date("m"), date("d"), date("Y")+1);
The first of the examples given here will use mktime() to create an Epoch Time variable called $tomorrow. This will use today's month (supplied using date("m"), today's date + 1 (supplied using date("d")+1), and today's year (using date("Y")).
The second does the same thing but in this case subtracts 1 from today's month in the expression date("m")-1, to get today's date last month.
The third expression on the other hand will get next year's date in Epoch Time into the variable $nextyear by adding 1 to today's year, in the expression date("Y")+1. Pretty much the same thing if you notice.
That's all for PHP dates and time. Of course PHP has other functions for manipulating dates and time. We will not try to exhaust all of them here. Maybe later when we get cranking! For now let's break new ground...