PHP CookBook Free Open Book

PHP CookBook

Previous Section Next Section

Recipe 3.10 Parsing Dates and Times from Strings

3.10.1 Problem

You need to get a date or time in a string into a format you can use in calculations. For example, you want to convert date expressions such as "last Thursday" into an epoch timestamp.

3.10.2 Solution

The simplest way to parse a date or time string is with strtotime( ) , which turns a variety of human-readable date and time strings into epoch timestamps:

$a = strtotime('march 10'); // defaults to the current year

3.10.3 Discussion

The grammar strtotime( ) uses is both complicated and comprehensive so the best way to get comfortable with it is to try out lots of different time expressions. If you're curious about its nuts and bolts, check out ext/standard/parsedate.y in the PHP source distribution.

The function strtotime( ) understands words about the current time:

$a = strtotime('now');
print strftime('%c',$a);
$a = strtotime('today');
print strftime('%c',$a);
Mon Aug 12 20:35:10 2002
Mon Aug 12 20:35:10 2002

It understands different ways to identify a time and date:

$a = strtotime('5/12/1994');
print strftime('%c',$a);
$a = strtotime('12 may 1994');
print strftime('%c',$a);
Thu May 12 00:00:00 1994
Thu May 12 00:00:00 1994

It understands relative times and dates:

$a = strtotime('last thursday');   // On August 12, 2002
print strftime('%c',$a);
$a = strtotime('2001-07-12 2pm + 1 month');
print strftime('%c',$a);
Thu Aug  8 00:00:00 2002
Mon Aug 12 14:00:00 2002

It understands time zones. When the following is run from a computer in EDT, it prints out the same time:

$a = strtotime('2002-07-12 2pm edt + 1 month');
print strftime('%c',$a);
Mon Aug 12 14:00:00 2002

However, when the following is run from a computer in EDT, it prints out the time in EDT when it is 2 P.M. in MDT (two hours before EDT):

$a = strtotime('2002-07-12 2pm mdt + 1 month');
print strftime('%c',$a);
Mon Aug 12 16:00:00 2002

If the date and time you want to parse out of a string are in a format you know in advance, instead of calling strtotime( ), you can build a regular expression that grabs the different date and time parts you need. For example, here's how to parse "YYYY-MM-DD HH:MM:SS" dates, such as a MySQL DATETIME field:

$date = '1974-12-03 05:12:56';
preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/',$date,$date_parts);

This puts the year, month, day, hour, minute, and second into $date_parts[1] through $date_parts[6]. (preg_match( ) puts the entire matched expression into $date_parts[0].)

You can use regular expressions to pull the date and time out of a larger string that might also contain other information (from user input, or a file you're reading), but if you're sure about the position of the date in the string you're parsing, you can use substr( ) to make it even faster:

$date_parts[0] = substr($date,0,4);
$date_parts[1] = substr($date,5,2);
$date_parts[2] = substr($date,8,2);
$date_parts[3] = substr($date,11,2);
$date_parts[4] = substr($date,14,2);
$date_parts[5] = substr($date,17,2);

You can also use split( );

$ar = split('[- :]',$date);
print_r($ar);
Array
(
    [0] => 1974
    [1] => 12
    [2] => 03
    [3] => 05
    [4] => 12
    [5] => 56
)

Be careful: PHP converts between numbers and strings without any prompting, but numbers beginning with a 0 are considered to be in octal (base 8). So, 03 and 05 are 3 and 5; but, 08 and 09 are not 8 and 9.

preg_match( ) and strtotime( ) are equally efficient in parsing a date format such as "YYYY-MM-DD HH:MM:SS", but ereg( ) is about four times slower than either. If you need the individual parts of the date string, preg_match( ) is more convenient, but strtotime( ) is obviously much more flexible.

3.10.4 See Also

Documentation on strtotime( ) at http://www.php.net/strtotime; the grammar for strtotime( ) is available at http://cvs.php.net/cvs.php/php4/ext/standard/parsedate.y.

    Previous Section Next Section
    Index: [SYMBOL][A][B][C][D][E][F][G][H][I][J][K][L][M][N][O][P][Q][R][S][T][U][V][W][X][Z]


         Main Menu
    Main Page
    Table of content
    Copyright
    Preface
    Chapter 1. Strings
    Chapter 2. Numbers
    Chapter 3. Dates and Times
    3.1 Introduction
    Recipe 3.2 Finding the Current Date and Time
    Recipe 3.3 Converting Time and Date Parts to an Epoch Timestamp
    Recipe 3.4 Converting an Epoch Timestamp to Time and Date Parts
    Recipe 3.5 Printing a Date or Time in a Specified Format
    Recipe 3.6 Finding the Difference of Two Dates
    Recipe 3.7 Finding the Difference of Two Dates with Julian Days
    Recipe 3.8 Finding the Day in a Week, Month, Year, or the Week Number in a Year
    Recipe 3.9 Validating a Date
    Recipe 3.10 Parsing Dates and Times from Strings
    Recipe 3.11 Adding to or Subtracting from a Date
    Recipe 3.12 Calculating Time with Time Zones
    Recipe 3.13 Accounting for Daylight Saving Time
    Recipe 3.14 Generating a High-Precision Time
    Recipe 3.15 Generating Time Ranges
    Recipe 3.16 Using Non-Gregorian Calendars
    Recipe 3.17 Program: Calendar
    Chapter 4. Arrays
    Chapter 5. Variables
    Chapter 6. Functions
    Chapter 7. Classes and Objects
    Chapter 8. Web Basics
    Chapter 9. Forms
    Chapter 10. Database Access
    Chapter 11. Web Automation
    Chapter 12. XML
    Chapter 13. Regular Expressions
    Chapter 14. Encryption and Security
    Chapter 15. Graphics
    Chapter 16. Internationalization and Localization
    Chapter 17. Internet Services
    Chapter 18. Files
    Chapter 19. Directories
    Chapter 20. Client-Side PHP
    Chapter 21. PEAR
    Colophon
    Index


    More Books
    PHP Hacks
    Processing Xml With Java - A Guide To Sax, Dom, Jdom, Jaxp, And Trax
    The Koran (Holy Qur'an)
    Macromedia Flash 8 Bible
    Search Engine Optimization for Dummies
    YouTube Traffic
    PHP 5 for Dummies
    Harry Potter and The Chamber of Secrets
    Harry Potter and the Sorcerer's Stone
    The Pilgrim's Progress
    Wireless Hacks
    Flash Hacks. 100 Industrial-Strength Tips & Tools
    PayPal Hacks. 100 Industrial-Strength Tips and Tools
    Amazon Hacks
    Pdf Hacks
    The Da Vinci Code
    Google Hacks
    The Holy Bible
    Windows XP For Dummies
    Harry Potter and the Half-Blood Prince
    Seo Book
    Upgrading and Repairing Networks
    Macromedia Dreamweaver 8 UNLEASHED
    Windows XP Annoyances
    Windows XP Hacks
    Microsoft Windows XP Power Toolkit
    Teach Yourself MS Office In 24Hours
    iPod & iTunes Missing Manual
    PC Hacks 100 Industrial-Strength Tips and Tools
    PC Overclocking, Optimization, and Tuning - 2th Edition
    PC Hardware In A Nutshell 3rd Edition
    PC Hardware in a Nutshell, 2nd Edition
    Upgrading and Repairing PCs
    Google for Dummies
    MySQL Cookbook
    Teach Yourself Macromedia Flash 8 In 24 Hours
    PHP CookBook
    Sams Teach Yourself JavaScript in 24 Hours
    PHP5 Manual
    Free Games Paper Airplanes
    500 Juegos Gratis 500 Giochi Gratis 500 Jeux Gratuits 500 Jogos Gratis 500 Kostenlose Spiele