Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Date Manipulation in PHP

Before you do anything with a date, you must first get it into a variable. What we are tryng to say is that you first grab the date from the system (the computer of course) and put it inside a variable, and then you can mess around with that variable until it starts screaming blue murder.

How?

Ok.. "How do we grab a date from the system and into a variable?"

Answer: "Using PHP's getDate() function - like this:"

$today = new getDate();

But you see getDate() is a sly fellow. He does not just give the date into the variable $today. He dumps an array into $today. Don't look at me like that arrays are here to stay. I warned ya'.

What I am trying to say is that, $today is an array - An Associative Array! that looks like this:

secondsNUMERIC, seconds
minutesNUMERIC, minutes
hoursNUMERIC, hour of the day [or night] :-)
mdayNUMERIC, day of the month (the date)
wdayNUMERIC day of the week where Sunday is 0, Mon =1, Tue =2...
monNUMERIC month of the year where Jan = 1, Feb=2...
yearThe year... of course NUMERIC
ydayNUMERIC, days elapsed since year began - Jan 1st is 1, Feb 3rd is 34...
weekdayTEXTUAL day of the week in Full - Monday, Tuesday...
monthTEXTUAL month in Full - January, February...

Phew! Ain't that a handful?!

Not quite. The getDate() function of course returns alot of things as the above list clearly indicates. To refer to any of the above items is easy. It is done by "de-referencing" the array like so:

<?php
$thisdate = getDate();
print("<b>$thisdate[weekday], $thisdate[mday] $thisdate[month] $thisdate[year]</b>");
?>

As you can see. It's harvest time already. We have here created a code snippet that prints the date. On my computer it produced something like this:

Friday, 4 May 2001

Copy the code snippet on every page on your website and there you are. You get a self-updating date that always make your site feel fresh and invigorated - sporting a new date every day! Fun would't you say?

It is fun only if you maintain a web page with 7 pages or so. The moment things start getting "titanic" you start cursing... "How am I expected to put a date on 20,000 pages... Even copy and paste ain't no good"

Don't worry pal. By the end of this lesson we will have a way out. So keep on reading. Date and Time Please...

<< Introduction to this Lesson | More Date manipulation >>

JamHitz Productions