Index
    Preface
      What This Book Is About
      What You Need to Know
      How This Book Is Organized
      How to Use This Book
      Conventions Used in This Book
      Using Code Examples
      How to Contact Us
      Web Site and Code Examples
      Acknowledgments
      Chapter 1.  Database Applications and the Web
      Section 1.1.  The Web
      Section 1.2.  Three-Tier Architectures
      Chapter 2.  The PHP Scripting Language
      Section 2.1.  Introducing PHP
      Section 2.2.  Conditions and Branches
      Section 2.3.  Loops
      Section 2.4.  Functions
      Section 2.5.  Working with Types
      Section 2.6.  User-Defined Functions
      Section 2.7.  A Working Example
      Chapter 3.  Arrays, Strings, and Advanced Data Manipulation in PHP
      Section 3.1.  Arrays
      Section 3.2.  Strings
      Section 3.3.  Regular Expressions
      Section 3.4.  Dates and Times
      Section 3.5.  Integers and Floats
      Chapter 4.  Introduction to Object-Oriented Programming with PHP 5
      Section 4.1.  Classes and Objects
      Section 4.2.  Inheritance
      Section 4.3.  Throwing and Catching Exceptions
      Chapter 5.  SQL and MySQL
      Section 5.1.  Database Basics
      Section 5.2.  MySQL Command Interpreter
      Section 5.3.  Managing Databases and Tables
      Section 5.4.  Inserting, Updating, and Deleting Data
      Section 5.5.  Querying with SQL SELECT
      Section 5.6.  Join Queries
      Section 5.7.  Case Study: Adding a New Wine
      Chapter 6.  Querying Web Databases
      Section 6.1.  Querying a MySQL Database Using PHP
      Section 6.2.  Processing User Input
      Section 6.3.  MySQL Function Reference
      Chapter 7.  PEAR
      Section 7.1.  Overview
      Section 7.2.  Core Components
      Section 7.3.  Packages
      Chapter 8.  Writing to Web Databases
      Section 8.1.  Database Inserts, Updates, and Deletes
      Section 8.2.  Issues in Writing Data to Databases
      Chapter 9.  Validation with PHP and JavaScript
      Section 9.1.  Validation and Error Reporting Principles
      Section 9.2.  Server-Side Validation with PHP
      Section 9.3.  JavaScript and Client-Side Validation
      Chapter 10.  Sessions
      Section 10.1.  Introducing Session Management
      Section 10.2.  PHP Session Management
      Section 10.3.  Case Study: Using Sessions in Validation
      Section 10.4.  When to Use Sessions
      Section 10.5.  PHP Session API and Configuration
      Chapter 11.  Authentication and Security
      Section 11.1.  HTTP Authentication
      Section 11.2.  HTTP Authentication with PHP
      Section 11.3.  Form-Based Authentication
      Section 11.4.  Protecting Data on the Web
      Chapter 12.  Errors, Debugging, and Deployment
      Section 12.1.  Errors
      Section 12.2.  Common Programming Errors
      Section 12.3.  Custom Error Handlers
      Chapter 13.  Reporting
      Section 13.1.  Creating a Report
      Section 13.2.  Producing PDF
      Section 13.3.  PDF-PHP Reference
      Chapter 14.  Advanced Features of Object-Oriented Programming in PHP 5
      Section 14.1.  Working with Class Hierarchies
      Section 14.2.  Class Type Hints
      Section 14.3.  Abstract Classes and Interfaces
      Section 14.4.  Freight Calculator Example
      Chapter 15.  Advanced SQL
      Section 15.1.  Exploring with SHOW
      Section 15.2.  Advanced Querying
      Section 15.3.  Manipulating Data and Databases
      Section 15.4.  Functions
      Section 15.5.  Automating Querying
      Section 15.6.  Table Types
      Section 15.7.  Backup and Recovery
      Section 15.8.  Managing Users and Privileges
      Section 15.9.  Tuning MySQL
      Chapter 16.  Hugh and Dave's Online Wines:A Case Study
      Section 16.1.  Functional and System Requirements
      Section 16.2.  Application Overview
      Section 16.3.  Common Components
      Chapter 17.  Managing Customers
      Section 17.1.  Code Overview
      Section 17.2.  Customer Validation
      Section 17.3.  The Customer Form
      Chapter 18.  The Shopping Cart
      Section 18.1.  Code Overview
      Section 18.2.  The Winestore Home Page
      Section 18.3.  The Shopping Cart Implementation
      Chapter 19.  Ordering and Shipping at the Online Winestore
      Section 19.1.  Code Overview
      Section 19.2.  Credit Card and Shipping Instructions
      Section 19.3.  Finalizing Orders
      Section 19.4.  HTML and Email Receipts
      Chapter 20.  Searching and Authentication in the Online Winestore
      Section 20.1.  Code Overview
      Section 20.2.  Searching and Browsing
      Section 20.3.  Authentication
      Appendix A.  Linux Installation Guide
      Section A.1.  Finding Out What's Installed
      Section A.2.  Installation Overview
      Section A.3.  Installing MySQL
      Section A.4.  Installing Apache
      Section A.5.  Installing PHP
      Section A.6.  What's Needed for This Book
      Appendix B.  Microsoft Windows Installation Guide
      Section B.1.  Installation Overview
      Section B.2.  Installing with EasyPHP
      Section B.3.  What's Needed for This Book
      Appendix C.  Mac OS X Installation Guide
      Section C.1.  Getting Started
      Section C.2.  Installing MySQL
      Section C.3.  Setting Up Apache and PHP
      Section C.4.  What's Needed for This Book
      Appendix D.  Web Protocols
      Section D.1.  Network Basics
      Section D.2.  Hypertext Transfer Protocol
      Appendix E.  Modeling and Designing Relational Databases
      Section E.1.  The Relational Model
      Section E.2.  Entity-Relationship Modeling
      Appendix F.  Managing Sessions in theDatabase Tier
      Section F.1.  Using a Database to Keep State
      Section F.2.  PHP Session Management
      Section F.3.  MySQL Session Store
      Appendix G.  Resources
      Section G.1.  Client Tier Resources
      Section G.2.  Middle-Tier Resources
      Section G.3.  Database Tier Resources
      Section G.4.  Security and Cryptography Resources
      Appendix H.  The Improved MySQL Library
      Section H.1.  New Features
      Section H.2.  Getting Started
      Section H.3.  Using the New Features
    Colophon
    Copyright



 

Previous Section  < Day Day Up >  Next Section

3.4 Dates and Times

There are several PHP library functions that work with dates and times. Most either generate a Unix timestamp or format a Unix timestamp in a human-readable form. Validation using dates, and working with the flexible PEAR Date package, is discussed in Chapter 9. In this section, we introduce timestamps and PHP library functions that work with Dates and Times.

3.4.1 Generating a Timestamp

A Unix timestamp consists of the number of seconds since the arbitrarily chosen time 1 January 1970 00:00:00 Greenwich Mean Time. Most systems represent a timestamp using a signed 32-bit integer, allowing a range of dates from December 13, 1901 through January 19, 2038. While timestamps are convenient to work with, care must be taken when manipulating timestamps to avoid integer overflow errors. While PHP automatically converts integers that overflow to floats, these values aren't valid timestamps.

In the Microsoft Windows environment, the timestamp functions don't support negative timestamps and can be used only with dates between January 1, 1970 and January 19, 2038.


3.4.1.1 Current time

PHP provides several functions that generate a Unix timestamp. The simplest:

integer time( )

returns the timestamp for the current date and time, as shown in this fragment:

// prints the current timestamp: e.g., 1064699133

print time( );

3.4.1.2 Creating timestamps with mktime( ) and gmmktime( )

To create a timestamp for a past or future date in the range December 13, 1901 through January 19, 2038, the mktime( ) and gmmktime( ) functions are defined:

int mktime(int hour, int minute, int second, int month, int day, int year [, int is_dst])
int gmmktime(int hour, int minute, int second, int month, int day, int year [, int is_dst])

Both create a timestamp from the parameters supplied; the parameters supplied to gmmktime( ) represent a GMT date and time, while the parameters supplied to mktime( ) represent the local time. This example creates a timestamp for 9:30 A.M. on June 18, 1998:

$aDate = mktime(9, 30, 0, 6, 18, 1998);

Both functions correctly handle parameter values that you might consider out-of-range. For example, the following call passes 14 for the month value, 29 for the day, and 2004 for the year, creating a time stamp for 1 March 2005:

// Creates a time stamp for 1 March 2005

$aDate = mktime(0, 0, 0, 14, 29, 2004);

Setting the month to 14 and the year to 2004 overflows to February in 2005 and setting the day to 29 overflows to the first of March. This characteristic allows scripts to add a quantum of time without range checking. The following example shows how 30 days can be added to a date and time:

$paymentPeriod = 30;  // Days



// generates a timestamp for 26 June 2002 by

// adding 30 days to 27 May 2002

$paymentDue = mktime(0, 0, 0, 5, 27 + $paymentPeriod, 2002);



// A different approach adds the appropriate number 

// of seconds to the timestamp for 27 May 2002

$paymentDue = mktime(0, 0, 0, 5, 27, 2002) 

              + ($paymentPeriod * 24 * 3600);

If the components of a date are outside the range of dates the function is defined for, -1 is returned. Both functions allow the supplied date to be interpreted as daylight savings time by setting the flag is_dst to 1.

The order of the arguments to these functions is unusual and easily confused. While the mktime( ) and gmmktime( ) functions are similar to the Unix mktime( ) function, the arguments aren't in the same order.

3.4.1.3 String to timestamp

The strtotime( ) function generates a timestamp by parsing a human-readable date and time (between December 13, 1901 and January 19, 2038) from the string time:

integer strtotime(string time)

The function interprets several standard representations of a date, as shown here:

// Absolute dates and times

$var = strtotime("25 December 2002");

$var = strtotime("14/5/1955");

$var = strtotime("Fri, 7 Sep 2001 10:28:07 -1000");



// The current time: equivalent to time( )

$var = strtotime("now");



// Relative to now

print strtotime("+1 day"); // tomorrow

print strtotime("-2 weeks"); // two weeks ago

print strtotime("+2 hours 2 seconds"); // in two hours and two seconds

Care should be taken when using strtotime( ) with user-supplied dates. It's better to limit the use of strtotime( ) to cases when the string to be parsed is under the control of the script. For example, it's used here to check a minimum age using a relative date:

// date of birth: timestamp for 16 August, 1982

$dob = mktime(0, 0, 0, 8, 16, 1982);



// Now check that the individual is over 18

if ($dob < strtotime("-18 years"))

    print "Legal to drive in the state of Victoria"; // prints

3.4.1.4 Subsecond times

A Unix timestamp represents a date and time accurate to the second, but many applications require times to be represented to the subsecond. PHP provides the function:

string microtime( )

The microtime( ) function returns a string that contains both a Unix timestamp in seconds and a microsecond component. The returned string begins with the microsecond component, followed by the integer timestamp:

// prints the time now in the format "microsec sec"

// Example: 0.55512200 1064700291

print microtime( );

One common use of the function microtime( ) is to generate an integer seed for a random-number generator:

// Generate a seed.

$seed = (float)microtime( ) * 1000000;



// prints (for example) 555206

print $seed;

Because the microsecond component appears at the start of the string returned from microtime( ), the returned value can be converted to a float with the (float) cast operator. Multiplying the float result by 1,000,000 ensures that you create a suitably varying integer.

The following fragment shows how you can use both the microsecond and second components to create a floating point representation of the time:

$parts = explode(" ", microtime( ));

$f = (float)$parts[0] + (int)$parts[1];



// prints (for example) 1064700291.56 

print $f;

3.4.2 Formatting a Date

While the Unix timestamp is useful in a program, it isn't a convenient display format. The date( ) and gmdate( ) functions return a human-readable formatted date and time:

string date(string format [, integer timestamp])
string gmdate(string format [, integer timestamp])

The format of the returned string is determined by the format argument. Passing in the optional timestamp argument can format a predetermined date. Otherwise, both functions format the current time. The format string uses the formatting characters listed in Table 3-3 to display various components or characteristics of the timestamp. To include characters without having the function interpret them as formatting characters, escape them with a preceding backslash character. The following examples show various combinations:

// Set up a timestamp for 08:15am 24 Aug 1974

$var = mktime(8, 15, 25, 8, 24, 1974);



// "24/08/1974"

print date('d/m/Y', $var);



// "08/24/74"

print date('m/d/y', $var);



// prints "Born on Saturday 24th of August" 

print date('\B\o\r\n \o\n l jS \of F', $var);

Table 3-3. Formatting characters used by the date( ) function

Formatting character

Meaning

a, A

"am" or "pm"; "AM" or "PM"

S

Two-character English ordinal suffix: "st", "nd", "rd", "th"

d, j

Day of the month: with leading zeros e.g., "01"; without e.g., "1"

D, l

Day of the week: abbreviated e.g., "Mon"; in full e.g., "Monday"

M, F

Month: abbreviated e.g., "Jan"; in full e.g., "January"

m, n

Month as decimal: with leading zeros: "01"-"12"; without: "1"-"12"

h, g

Hour 12-hour format: with leading zeros e.g., "09"; without e.g., "9"

H, G

Hour 24-hour format: with leading zeros e.g., "01"; without e.g., "1"

I

Minutes:"00" to "59"

s

Seconds: "00" to "59"

Y, y

Year: with century e.g., "2004"; without century e.g., "04"

r

RFC-2822 formatted date: e.g., "Tue, 29 Jan 2002 09:15:33 +1000" (added in PHP 4.0.4)

w

Day of the week as number: "0" (Sunday) to "6" (Saturday)

t

Days in the month: "28" to "31"

z

Days in the year: "0" to "365"

B

Swatch Internet time

L

Leap year: "0" for normal year; "1" for leap year

I

Daylight savings time: "0" for standard time; "1" for daylight savings

O

Difference to Greenwich Mean Time in hours: "+0200"

T

Time zone setting of this machine

Z

Time zone offset in seconds: "-43200" to "43200"

U

Seconds since the epoch: 00:00:00 1/1/1970


PHP also provides the equivalent functions:

string strftime(string format [, integer timestamp])
string gmstrftime(string format [, integer timestamp])

The format string uses the same % sequence formatting character sequences as the C library function strftime( ). For example:

// Prints "24/08/1974 08:15:25"

print strftime("%d/%m/%Y %H:%M:%S", mktime(8, 15, 25, 8, 24, 1974));



// Prints "08/24/1974"

print strftime("%D", mktime(8, 15, 25, 8, 24, 1974));

The result of some % sequences used by strftime( ) and gmstrftime( ) depends on the locale settings. The following sets the locale so the printed date used the Estonian language and conventions:

setlocale (LC_TIME, 'es');



// prints "laupäev 24 august 1974"

print strftime ("%A %d %B %Y", mktime(8, 15, 25, 8, 24, 1974));

Formatting sequences supported by strftime( ) and gmstrftime( ) are shown in Table 3-4. Some of these % sequences are not supported under Windows as noted.

Table 3-4. Formatting characters used by the strftime( ) and gmstrftme( ) functions

Formatting sequence

Meaning

%a, %A

Day of the week dependant on locale settings: abbreviated e.g., "Mon"; in full e.g., "Monday".

%b, %B

Month: abbreviated e.g., "Jan"; in full e.g., "January"

%c, %x, %X

Default Date and Time format for the local settings: with time e.g., "01/27/04 22:06:03"; without time e.g., "01/27/04"; without the date e.g., "06:03"

%C

Century e.g., "04" for 2004 (does not work with Windows)

%d

Day of month padded with leading zero e.g., "01"

%D

Same as "%m/%d/%y" (does not work with Windows)

%e

Day of month padded with leading space e.g., "1" (does not work with Windows)

%H, %I

Hour: 24-hour format with leading zero e.g., "15"; 12-hour format with leading zero e.g., "03"

%j

Day of the year: "001" to "366"

%m

Month with leading zero e.g., "01"

%M

Minute with leading zero e.g., "01"

%p

"AM" or "PM". Value dependant on locale settings

%r

Time in am/pm notation (does not work with Windows)

%R

Time in 24 hour notation (does not work with Windows)

%S

Seconds with leading zero

%T

Same as "%H:%M:%S" (does not work with Windows)

%u, %w

Day of the week as a decimal: 1-7 with "1" = Monday, "2" = Tuesday, etc..; 0-6 with "0" = Sunday, "1" = Monday, etc.. %u (does not work with Windows)

%U

Week number in a year where the first week starts with the first Sunday in the year

%V

Week number in a year where the first week is the week, with at least four days, starting on a Monday, in the current year. This is the ISO 8601:1988 definition of the week number (does not work with Windows)

%W

Week number in a year where the first week starts with the first Monday in the year

%y, %Y

Year: without the century e.g., "04" for 2004; with the century e.g., "2004"

%Z

Time zone information e.g., "AUS Eastern Standard Time"

%%

Literal % character


3.4.3 Validating a Date

The function checkdate( ) returns true if a given month, day, and year form a valid Gregorian date:

boolean checkdate(integer month, integer day, integer year)

This function isn't based on a timestamp and so can accept any dates in the years 1 to 32767. It automatically accounts for leap years.

// Works for a wide range of dates

$valid = checkdate(1, 1, 1066); // true

$valid = checkdate(1, 1, 2929); // true



// Correctly identify bad dates

$valid = checkdate(13, 1, 1996); // false

$valid = checkdate(4, 31, 2001); // false



// Correctly handles leap years

$valid = checkdate(2, 29, 1996); // true

$valid = checkdate(2, 29, 2001); // false

    Previous Section  < Day Day Up >  Next Section







    Copyright © 2010 | Domen maybe sale - bye this domen