Returning the current timestamp with the time() function
May 28, 2002
Returning the current timestamp is easy
print time();
displays:
1020961685
You can see how many seconds have passed since I wrote this by comparing your
results. And that gives you a clue as to how we can do date and time arithmetic.
By subtracting the two timestamps, you can see how many seconds have elapsed,
and once you have that, you can convert it into more friendly formats with some
of the other functions.
Storing the current date and time in an array with the getdate()
function
The date function is very useful for displaying a date, but is not ideal for
returning useful data for your applications to work with. There's a better
function to use - getdate(). Given a timestamp, it returns an associative array
with the following elements:
| "seconds" |
seconds |
| "minutes" |
minutes |
| "hours" |
hours |
| "mday" |
day of the month |
| "wday" |
day of the week, numeric : from 0 as Sunday up to 6 as Saturday |
| "mon" |
month, numeric |
| "year" |
year, numeric |
| "yday" |
day of the year, numeric; i.e. "299" |
| "weekday" |
day of the week, textual, full; i.e. "Friday" |
| "month" |
month, textual, full; i.e. "January" |
| "0" |
timestamp |
|
By default, it takes the current time, so getdate() is equivalent to
getdate(time()). Take a look at the following snippet of code:
$datetime_array = getdate(); //populate associative array
//display time
print "Current time: ".$datetime_array{hours}.":
".$datetime_array{minutes};
// display all elements of the associative array
foreach($datetime_array as $key=>$val) {
print " $key: $val";
}
Note:Color coded lines have been split for display purposes
displays:
Current time: 23: 35
seconds: 32
minutes: 35
hours: 23
mday: 9
wday: 4
mon: 5
year: 2002
yday: 128
weekday: Thursday
month: May
0: 1020980132
Using localtime() as an alternative to getdate()
The localtime function returns an alternative array to getdate(). It is OS
dependant however, and uses the underlying C function call. It takes an optional
two parameters, the first is the timestamp (defaults to current time), and the
second determines whether the array is associative or numeric (0 for numeric, 1
for associative). The array has has the following elements.
| tm_sec |
seconds |
| tm_min |
minutes |
| tm_hour |
hour |
| tm_mday |
day of the month |
| tm_mon |
month of the year (0 to 11) |
| tm_year |
Years since 1900 |
| tm_wday |
Day of the week (0 to 6 for Sunday to Saturday) |
| tm_yday |
Day of the year |
| tm_isdst |
Is daylight savings time in effect |
Date and Time in PHP
Date and Time in PHP
Generating a timestamp with the mktime() function
|