March 11, 2008

Dates and Time in PHP

In this section we will be guided through PHP's functions related to time.
1. getdate
One of the most important functions is the getdate function. It returns the current date in an array of values that can be used for further treatment. Let's take a look at an example:
<?php        
$mydate = getdate();
echo "seconds: ".$mydate['seconds']."<br>";
echo "minutes: ".$mydate['minutes']."<br>";
echo "hours: ".$mydate['hours']."<br>";
echo "mday: ".$mydate['mday']."<br>";
echo "wday: ".$mydate['wday']."<br>";
echo "mon: ".$mydate['mon']."<br>";
echo "year: ".$mydate['year']."<br>";
echo "yday: ".$mydate['yday']."<br>";
echo "weekday: ".$mydate['weekday']."<br>";
echo "month: ".$mydate['month']."<br>";
?>

First the current time is computed. In the next step, the values stored in the array are displayed.
seconds: 2
minutes: 17
hours: 16
mday: 02
wday: 6
mon: 1
year: 2008
yday: 11
weekday: Saturday
month: January

2. date and mktime
Sometimes we want a date to be displayed in a certain format. For this purpose, we can use a function called date. Let's take a look at an example:
<?php     
echo date("Y-m-d H:i:s");
?>

The date is displayed in the same way we have already seen when dealing with PostgreSQL:
2008-01-02 21:38:19  

However, with the help of date we can do even more. In general the date function is used to format a date to our needs. If we want to format any date, we pass it to the function; otherwise, the current date will be used. Let's see how this can be done:
<?php  
echo date("Y-m-d H:i:s", mktime(23,9,4,02,1,2008))."<br>";
echo date("Y-m-d, h a", mktime(23,9,4,02,1,2008))."<br>";
echo date("Y-m-d, z", mktime(23,9,4,02,1,2008))."<br>";
?>

The first line displays the date passed to the function by computing the result of the mktime function. mktime takes the input parameters and makes a date out of it. The result of this function can be used as input for the date function. In the first example the date including the time is displayed. In the second example we can see that 23 o'clock is equal to 11 p.m. The third example shows how many days in the year have passed until the date passed to the function.
If we execute the script, three lines will be displayed:
2008-02-01 23:09:04  
2008-02-01, 11 pm
2008-02-01, 334

So far, we have seen the most important flags of the date command. The following list shows all the flags and formats accepted by date:

  • a— Displays "am" (ante meridiem) or "pm" (post meridiem)
  • A— Displays "AM" or "PM"
  • B— Swatch Internet time
  • d— Two digits defining the day of the month
  • D— Displays day of week using three letters
  • F— Displays month as text
  • g— Displays the hour as number from 1 to 12
  • G— Displays the hour as number from 0 to 23
  • h— Displays the hour using two digits (01–12)
  • H— Displays the hour using two digits (00–23)
  • i— Displays the minutes as two digits (00–59)
  • I— "1" if Daylight Savings Time, "0" otherwise
  • j— Day of the month (1–31)
  • l— Displays day of the week as text
  • L— Boolean value defining whether a year is a leap year
  • m— Displays month using two digits (01–12)
  • M— Displays months using text
  • n— Displays month without using leading zero
  • O— Difference relative to GMT
  • r— RFC-822 formatted date
  • s— Displays second using two digits (00–59)
  • S— Displays English ordinal suffixes
  • t— Number of days in a given month
  • T— Displays the time zone the local machine is in
  • U— Seconds since Unix starting time (January 1, 1970)
  • w— Displays day of week as number (0=Sunday; 6=Saturday)
  • W— ISO-8601 week number of year, weeks starting on Monday
  • Y— Displays year using 4 digits (2004)
  • y— Displays year using 2 digits (99)
  • z— Day of year
  • Z— Time zone offset in seconds


3. checkdate
To find out if a date is valid, PHP provides a function called checkdate. The function accepts three parameters. The first one defines the month, the second one the day, and the third one the year of the date. When checking the date, leap years are taken into consideration.
Let's see how this function can be used:
<?php       
if (checkdate(12, 1, 2008)) {
echo "date valid<br>\n";
}
else {
echo "date invalid<br>\n";
}
if (checkdate(12, 1, 200800)) {
echo "date valid<br>\n";
}
else {
echo "date invalid<br>\n";
}
?>

The first date is valid, but the second one isn't:
date valid 
date invalid


4.gettimeofday

The gettimeofday function returns the current date in an array. In contrast to the getdate function, gettimeofday returns microseconds, seconds, the minutes west of Greenwich, and the type of DST (Daylight Saving Time) correction. The next listing contains an example:
<?php    
$mydate = gettimeofday();
echo "sec: ".$mydate['sec']."<br>\n";
echo "usec: ".$mydate['usec']."<br>\n";
echo "minuteswest: ".$mydate['minuteswest']."<br>\n";
echo "dsttime: ".$mydate['dsttime']."<br>\n";
?>

Four lines will be displayed:
sec: 1205255935
usec: 546879
minuteswest: -420
dsttime: 0

The third line especially will be important because the content of the third field will help we when working with time zones. In this scenario we are two hours east of Greenwich (two hours in front).
5. gmtime
If we want a result to be displayed using GMT (Greenwich Mean Time), we can use gmtime instead of the date function. The advantage of this function is that we don't have to retrieve the current time zone and compute the offset to GMT. gmtime can do all these things for we:
<?php         
echo date ("M d Y H:i:s", mktime (22,39,18,02,1,2008))."<br>";
echo gmdate ("M d Y H:i:s", mktime (22,39,18,02,1,2008))."<br>";
?>

If we take a look at the next example, we will find out that the second line differs from the first line:
February 01 2008 22:39:18 
February 01 2008 21:39:18

6.gmmktime
The gmmktime function can be used to compute a Unix timestamp for a GMT date. Let's take a look at the syntax overview of the command:
int gmmktime (int hour, int minute, int second, int month, int day,  int year [, int is_dst])  

To compute the number of seconds passed until Unix starting time, we can use a script like the following:
<?php       
$x = gmmktime (1, 17, 53, 1, 13, 2008);
echo "x: $x<br>\n";
?>

More than one billion seconds have passed since Unix starting time:
x: 1200187073    



7 gmstrftime and strftime
To format a timestamp according to our needs, PHP provides two additional functions, which will be discussed in this section: gmstrftime and strftime. The difference between the two functions is that gmstrftime returns the data as GMT, whereas strftime uses the local settings to display the time. Let's take a look at an example:
<?php    
setlocale ('LC_TIME', 'en');
echo "GMT:<br>\n";
echo gmstrftime ("%b %d %Y %H:%M:%S",mktime (23, 19, 8 ,03 ,1 ,2008))."<br><br>\n";
echo "local settings:<br>\n";
echo strftime ("%b %d %Y %H:%M:%S",mktime (23, 19, 8 ,03 ,1 ,2008))."<br>\n";
?>

First the local setting is defined. In the next step the date passed to the mktime function is formatted according to the template passed to gmstrftime, and strftime functions as the first parameter. If we execute the script, several lines will be returned as we can see in the next listing:
GMT:  Mar 01 2008 16:19:08    
local settings: Jan 01 2008 23:19:08

8. localtime


PHP's localtime function is similar to Perl's localtime function. It returns the current local time as an array consisting of all necessary components:
<?php          
$mydate = localtime();
echo "tm_sec: ".$mydate[0]."<br>\n";
echo "tm_min: ".$mydate[1]."<br>\n";
echo "tm_hour: ".$mydate[2]."<br>\n";
echo "tm_mday: ".$mydate[3]."<br>\n";
echo "tm_mon: ".$mydate[4]."<br>\n";
echo "tm_year: ".$mydate[5]."<br>\n";
echo "tm_wday: ".$mydate[6]."<br>\n";
echo "tm_yday: ".$mydate[7]."<br>\n";
echo "tm_isdst: ".$mydate[8]."<br>\n";
?>

The array returned by PHP can be indexed easily, so it is an easy task to retrieve the data we need. When we execute the script, the array will be displayed line by line:
tm_sec: 59 
tm_min: 46
tm_hour: 13
tm_mday: 13
tm_mon: 0
tm_year: 102
tm_wday: 0
tm_yday: 12
tm_isdst: 0

9. time
PHP's time function returns the current Unix timestamp:
<?php  
echo time();
?>

More than a billion seconds have passed since Unix starting time:
1205254851

10. strtotime
To convert a string to a timestamp, PHP provides a function called strtotime. Various input formats are accepted by the function, so almost any useful format can be converted to a timestamp. The next example shows a variety of input formats accepted by strtotime:
<?php         
# valid dates:
echo "March 11 2008: ".strtotime("March 11 2008")."<br>\n";
echo "March 11 02: ".strtotime("March 11 02")."<br>\n";
echo "2008/3/11: ".strtotime("2008/3/11")."<br>\n";
echo "2008-3-11: ".strtotime("2008-3-11")."<br>\n";
echo "2008/3/11 18:32:17: ".strtotime("2008/3/11 18:32:17")."<br>\n";
echo "2008-3-11 18:32:17: ".strtotime("2008-3-11 18:32:17")."<br>\n";
# abbreviation
echo "3 months 12 days 29 seconds: ". strtotime("3 months 12 days 29 seconds")."<br>\n";
# in valid dates:
echo "13.1.2008: ".strtotime("13.1.2008");
?>

All formats but the German format we can see in the last line are accepted by PHP. As we have already seen, Unix timestamps are based on seconds. With the help of these simple formats, Unix timestamps are portable and interacting with other software products is easy. When we execute the script, we will see how the result is displayed:
 March 11 2008: 1205168400
March 11 02: 1205168400
2008/3/11: 1205168400
2008-3-11: 1205168400
2008/3/11 18:32:17: 1205235137
2008-3-11 18:32:17: 1205235137
3 months 12 days 29 seconds: 1019742570
13.1.2008: -1


11. microtime


Retrieving the current timestamp in microseconds, we can use the microtime function as explained in the next listing:
<?php      
$data = microtime();
$comp = split(" ", $data);
echo "usec: $comp[0]<br>\n";
echo "sec: $comp[1]<br>\n";
?>

The result of microtime is one string consisting of two components. The first one contains the number of microseconds. The second component contains the seconds that have passed since Unix starting time. If we execute the script in the previous listing, the result could look like this:
usec: 0.53125500
sec: 1205255325

Share

0 comments:

Blogger template 'PlainFish' by Ourblogtemplates.com 2008