note 102705 added to function.strtotime
[email protected] Tue, 1 Mar 2011 08:17:05 -0800
| Newsgroups | php.notes |
|---|---|
| Message-ID | <[email protected]> |
PHP strtotime() does not handle the ISO8601 notation for "duration." This handles the most likely subset of the duration standard (the one that is used by eBay).
<?php // RAY_duration_strtotime.php
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
// WHAT DOES THIS STRING MEAN?
$str = 'P1Y3M2DT16H2M40S';
// IT IS THE ISO8601 FORMAT FOR A DURATION.
// SEE http://en.wikipedia.org/wiki/ISO_8601
// IT MEANS THIS:
// P = Pending (INDICATOR OF ISO8601 DURATION)
// 1Y = 1 Year
// 3M = 3 Months
// 2D = Two Days
// T = Time Separator (M is ambiguous)
// 16H = Sixteen hours
// 2M = Two minutes
// 40S = Forty seconds
// STRTOTIME CANNOT HANDLE ISO-8601 DURATIONS
$dur = strtotime($str);
var_dump($dur);
echo "<br/>";
// GET THE DURATION IN SECONDS FOR USE IN ARITHMETIC
$dur = duration_strtotime($str);
echo "<br/>" . number_format($dur) . ' SECONDS';
// USE THE DURATION IN ARITHMETIC
echo "<br/>" . date('r', strtotime("NOW + $dur SECONDS"));
// A FUNCTION TO MAKE A DURATION STRING INTO A NUMBER OF SECONDS
function duration_strtotime($str, $sho=FALSE)
{
// REMOVE THE AMBIGUITY OF MONTH AND MINUTE -- MAKE MONTH = X
$arr = explode('T', $str);
$arr[0] = str_replace('M', 'X', $arr[0]);
$new = implode('T', $arr);
// EXPAND THE STRING INTO SOMETHING SENSIBLE
$new = str_replace('S', 'seconds ', $new);
$new = str_replace('M', 'minutes ', $new);
$new = str_replace('H', 'hours ', $new);
$new = str_replace('T', ' ', $new);
$new = str_replace('D', 'days', $new);
$new = str_replace('X', 'months ', $new);
$new = str_replace('Y', 'years ', $new);
$new = str_replace('P', NULL, $new);
if ($sho) var_dump($new);
// RETURN THE NUMBER OF SECONDS IN THE DURATION
return strtotime($new) - strtotime('NOW');
}
----
Server IP: 69.147.83.197
Probable Submitter: 98.169.58.122
----
Manual Page -- http://www.php.net/manual/en/function.strtotime.php
Edit -- https://master.php.net/note/edit/102705
Del: integrated -- https://master.php.net/note/delete/102705/integrated
Del: useless -- https://master.php.net/note/delete/102705/useless
Del: bad code -- https://master.php.net/note/delete/102705/bad+code
Del: spam -- https://master.php.net/note/delete/102705/spam
Del: non-english -- https://master.php.net/note/delete/102705/non-english
Del: in docs -- https://master.php.net/note/delete/102705/in+docs
Del: other reasons-- https://master.php.net/note/delete/102705
Reject -- https://master.php.net/note/reject/102705
Search -- https://master.php.net/manage/user-notes.php