2.21 Parsing Dates and Times from Strings


You want to extract the date and time from a string such as 10-24-2000 and convert it into a usable form (such as seconds since the UNIX epoch began ).

Technique

Use the explode() function along with the mktime () function:

 <?php list ($month, $day, $year) = explode ("-", $date); $epoch = mktime (0, 0, 0, $month, $day, $year); ?> 

Comments

You're probably saying (as I once did) that finding the number of seconds since the UNIX epoch began on January 1, 1970 is not really that helpful. However, I contend that it helps you in a great many things. For example, in recipe 2.19, we used it to have a universal time function. In recipe 2.18, we used it to add dates and times, and just last recipe (recipe 2.20) we found out that UNIX timestamps are in epoch seconds. So, finding the epoch seconds from a user -submitted string is extremely useful when doing any type of conversions with time.

In the solution code, we use the list statement along with explode() to first split the array by the "-" delimiter and then assign each element to $month , $day , and $year . Then we call the mktime() function, which returns the number of seconds since January 1, 1970, and our conversions are complete.

You can parse the date and time out of strings such as "Mary bought her lamb on 6/15/99" by using the following method:

 <?php preg_match ("#(\d+)/(\d+)/(\d+)#", $string, $date); ?> 

Then $date[0] would contain the entire date, $date[1] would contain 6 , $date[2] would contain 15 , and $date[3] would contain 99 .

As an easter egg, PHP also has a built-in function, strtotime() , that will try to figure out the format of the date in the input string and return a timestamp for it. It recognizes most common date formats, such as "05/02/2000" , "May 2, 2000 20:00" , and so on. You can omit parts of the date, such as "May 2" and strtotime() will use the current date and time for the remainder. Here is an example:

 <?php $birth_time = "November 2, 1976 01:50am"; $birth_timestamp = strtotime ($birth_time); print "You are "; print number_format (time() - $birth_timestamp); print " seconds old!"; ?> 

strtotime() is also very handy for calculating timestamps for relative offsets. You can use it, for example, to find out what the date will be 40 days from some starting date:

 <?php $start_date = mktime (0, 0, 0, 06, 07, 2000); $target_date = strtotime ("+40 days", $start_date); ?> 

The relative offset can be positive or negative and can be seconds, minutes, hours, days, months, and years . You can even combine it, like so:

 <?php $start_date = mktime(0, 0, 0, 06, 07, 2000); $target_date = strtotime("+4 months +5 days", $start_date); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net