strptime

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

strptime Analiza una fecha/hora generada con strftime()

Descripción

strptime(string $date, string $format): array

strptime() devuelve una matriz con la fecha date analizada, o false si se produjo un error.

Los nombres del mes y del día de la semana y otras cadenas dependientes del lenguaje están subordinados a la configuración regional local establecida con setlocale() (LC_TIME).

Parámetros

date (string)

La cadena a analizar (p.ej. devuelta por strftime()).

format (string)

El formato usado en date (p.ej. el mismo que el usado en strftime()). Observe que algunas de las opciones de formato disponibles en strftime() pueden no tener ningún efecto en strptime(); el subconjunto exacto que está soportado variará según el sistema operativo y a la biblioteca de C que esté en uso.

Para más información sobre las opciones de formato, lea la página de strftime().

Valores devueltos

Devuelve una matriz o false en caso de error.

Los siguietens parámetros son devueltos en la matriz
parámetros Descripción
"tm_sec" Segundos después del minuto (0-61)
"tm_min" Minutos después de la hora (0-59)
"tm_hour" Hora desde la medianoche (0-23)
"tm_mday" Día del mes (1-31)
"tm_mon" Meses desde Enero (0-11)
"tm_year" Años desde 1900
"tm_wday" Días desde el Domingo (0-6)
"tm_yday" Días desde el 1 de Enero (0-365)
"unparsed" la parte de date que no fue reconocida usando el formato format especificado

Ejemplos

Ejemplo #1 Ejemplo de strptime()

<?php
$formato
= '%d/%m/%Y %H:%M:%S';
$strf = strftime($formato);

echo
"$strf\n";

print_r(strptime($strf, $formato));
?>

El resultado del ejemplo sería algo similar a:

03/10/2004 15:54:19

Array
(
    [tm_sec] => 19
    [tm_min] => 54
    [tm_hour] => 15
    [tm_mday] => 3
    [tm_mon] => 9
    [tm_year] => 104
    [tm_wday] => 0
    [tm_yday] => 276
    [unparsed] =>
)

Notas

Nota: Esta función no está implementada en plataformas Windows.

Nota:

Internamente, esta función llama a la función strptime() proporcionada por la biblioteca C del sistema. Esta función puede presentar diferencias notables de comportamiento en diferentes sistemas operativos. Se recomienda el uso de date_parse_from_format(), a la cuál no le afectan estas cosas, en PHP 5.3.0 y posterior.

Nota:

"tm_sec" incluye segundos intercalares (actualmente hasta 2 por año). Para más información acerca de los segundos intercalares, vea el » artículo de Wikipedia sobre segundos intercalares.

Nota:

Antes de PHP 5.2.0, esta función podía devolver un comportamiento indefinido. En particular, las entradas "tm_sec", "tm_min" y "tm_hour" devolverían valores indefinidos.

Ver también

add a note add a note

User Contributed Notes 13 notes

up
4
P.
16 years ago
If strptime() fails to match all of the format string and therefore an error occurred the function returns NULL.
up
7
131
12 years ago
Another portage for windows (from ex/yks toolkit)
<?php
//  public static
function strptime($date, $format) {
   
$masks = array(
     
'%d' => '(?P<d>[0-9]{2})',
     
'%m' => '(?P<m>[0-9]{2})',
     
'%Y' => '(?P<Y>[0-9]{4})',
     
'%H' => '(?P<H>[0-9]{2})',
     
'%M' => '(?P<M>[0-9]{2})',
     
'%S' => '(?P<S>[0-9]{2})',
    
// usw..
   
);

   
$rexep = "#".strtr(preg_quote($format), $masks)."#";
    if(!
preg_match($rexep, $date, $out))
      return
false;

   
$ret = array(
     
"tm_sec"  => (int) $out['S'],
     
"tm_min"  => (int) $out['M'],
     
"tm_hour" => (int) $out['H'],
     
"tm_mday" => (int) $out['d'],
     
"tm_mon"  => $out['m']?$out['m']-1:0,
     
"tm_year" => $out['Y'] > 1900 ? $out['Y'] - 1900 : 0,
    );
    return
$ret;
  }
?>
up
3
peter at removethisplease dot ddcrew dot com
9 years ago
emanuil's comment / mktime() example is wrong, in that his mktime() line should have $ts['tm_mon'] + 1 because strptime() returns the months zero-based, while mktime() expects it one-based.
up
2
svenr at selfhtml dot org
17 years ago
If you need strptime but are restricted to a php version which does not support it (windows or before PHP 5), note that MySQL since Version 4.1.1 offers (almost?) the same functionality with the STR_TO_DATE function.

See http://dev.mysql.com/doc/refman/4.1/en/date-and-time-functions.html
up
2
Malte Starostik
17 years ago
It says "Parse a time/date generated with strftime()" but that's not entirely correct -- While strptime("2006131", "%Y%W%u") works as expected, strptime("2006131", "%G%V%u") returns false instead of reversing the equivalent - and unambiguous - strftime() usage.  I suspect that's because glibc doesn't support that.  Anyway, this docu page fails to mention that apparently not all format components supported by strftime() can be used with strptime().
up
1
arnold at nijboer dot it
10 years ago
the example (or the function) has an inconsistancy with other PHP functions.

the example returns 104 for the year 2004

while in the strftime function the 2 digit year is 70-100 for 1970-2000
and 1-69 for 2001-2069
up
1
Quietust
15 years ago
On some systems, particularly those of BSD lineage (such as FreeBSD and MacOS X), the tm_wday and tm_yday fields are only initialized if requested explicitly (that is, if the %a/%A/%u/%w and %j formats are specified), while others such as Linux and Solaris will calculate them automatically.
up
1
jojyjob at gmail dot com
17 years ago
/***Finding the days of a week ***/

<?php

$out
= pre(); 
$outpre=nextweek();
$td=date("Y-m-d");
$result = array_reverse($outpre);
//print_r($result);
array_push($result,$td);
$newarray = array_merge($result,$out);

  foreach(
$newarray as $date1){
    echo
$date1;
    echo
"<br>";
}

//print_r($out);
//print_r($newarray);

function pre() 
{
$monP=0;
$tueP=1;
$wedP=2;
$thuP=3;
$friP=4;
$satP=5;
$sunP=6;
 
$td=date("Y-m-d");  
//echo $td;
$tdname=date("l"); 
  switch(
$tdname)
  {
   case
"Monday":
      
$rep=$monP;
       break;
   case
"Tuesday":
      
$rep=$tueP;
       break;
   case
"Wednesday":
      
$rep=$wedP;
       break;
   case
"Thursday":
      
$rep=$thuP;
       break;
   case
"Friday":
      
$rep=$friP;
       break;
   case
"Saturday":
      
$rep=$satP;      
       break;
   case
"Sunday":
      
$rep=$sunP;      
       break;      
   default:
       echo
"Sorry";      
  }


//echo $tdname."<br>";  
//echo $rep;
$datstart =$td/* the starting date */
//$rep = 12;  /* number of future dates to display */
$nod = 1/* number of days in the future to increment the date */
$nom = 0/* number of months in the future to increment the date */
$noy = 0/* number of years in the future to increment the date */
$precon=future_date($datstart,$rep,$nod,$nom,$noy);
return
$precon;
}
function
future_date($datstart,$rep,$nod,$nom,$noy) {
$pre = array();
  while (
$rep >= 1) {
   
$datyy=substr($datstart,0,4);
   
$datmm=substr($datstart,5,2);
   
$datdd=substr($datstart,8,2);
   
$fda=$datdd - $nod;
   
$fmo=$datmm - $nom;
   
$fyr=$datyy -$noy;
   
$dat1=date("Y-m-d", mktime(0,0,0,$fmo,$fda,$fyr))."<BR>";
   
array_push($pre,$dat1);
   
//echo $dat1;
   
$datstart=$dat1;
   
$rep--;
  }
  return
$pre;
}

function
nextweek()
{
$monN=6;
$tueN=5;
$wedN=4;
$thuN=3;
$friN=2;
$satN=1;
$sunN=0;

$td=date("Y-m-d");  
$tdname=date("l"); 
  switch(
$tdname)
  {
   case
"Monday":
      
$rep=$monN;
       break;
   case
"Tuesday":
      
$rep=$tueN;
       break;
   case
"Wednesday":
      
$rep=$wedN;
       break;
   case
"Thursday":
      
$rep=$thuN;
       break;
   case
"Friday":
      
$rep=$friN;
       break;
   case
"Saturday":
      
$rep=$satN;      
       break;
   case
"Sunday":
      
$rep=$sunN;      
       break;      
   default:
       echo
"Sorry";      
  }


//echo $tdname."<br>";  
//echo $rep;
$datstart =$td/* the starting date */
//$rep = 12;  /* number of future dates to display */
$nod = 1/* number of days in the future to increment the date */
$nom = 0/* number of months in the future to increment the date */
$noy = 0/* number of years in the future to increment the date */

$con = future_date1($datstart,$rep,$nod,$nom,$noy);
return
$con;
}

function
future_date1($datstart,$rep,$nod,$nom,$noy) {
$pre = array();
  while (
$rep >= 1) {
   
$datyy=substr($datstart,0,4);
   
$datmm=substr($datstart,5,2);
   
$datdd=substr($datstart,8,2);
   
$fda=$datdd + $nod;
   
$fmo=$datmm + $nom;
   
$fyr=$datyy + $noy;
   
$dat1=date("Y-m-d", mktime(0,0,0,$fmo,$fda,$fyr))."<BR>";
   
array_push($pre,$dat1);
   
//echo $dat1;
   
$datstart=$dat1;
   
$rep--;
  }
  return
$pre;
}

?>
up
0
emanuil dot tolev at gmail dot com
11 years ago
Be careful: the output of strptime() ( http://www.php.net/manual/en/function.strptime.php ) cannot always be used with mktime() ( http://www.php.net/manual/en/function.mktime.php )!

This is not because of what platform you're using or what format strings glibc supports. This is simply because strptime returns years SINCE 1900 (as documented above) and mktime expects a year in the format returned by date('Y') - which is the full 4 digits.

Therefore, if you parse a date with strptime and want to give it to mktime, you have to pass in ($parsed_time['tm_year'] + 1900) as the year parameter to mktime(), not just $parsed_time['tm_year'].

This issue arose when I had a date like: 19/06/2012 12:03:34. strtotime() doesn't parse this particular format, so I needed custom parsing. So I ended up with:
1. $ts = $service->getNeededDateTime();
2. $ts = strptime($ts, '%d/%m/%Y %H:%M:%S');
3. $ts = mktime($ts['tm_hour'], $ts['tm_min'], $ts['tm_sec'],
      $ts['tm_mon'], $ts['tm_mday'], ($ts['tm_year'] + 1900));
up
0
Altar 2010
15 years ago
If you want to parse a date or a /time in windows env, i re-write strptime function for windows.

I use the same param and i return the same think that the original one.
I use sscanf to parde the string.
Only some format can be parsed (%S, %M, %H, %d, %m, %Y)

See this page (because the function is too big for this notes)
http://sauron.lionel.free.fr/?page=php_lib_strptime

preview :
<?php
/**
* Parse a time/date generated with strftime().
*
* This function is the same as the original one defined by PHP (Linux/Unix only),
*  but now you can use it on Windows too.
*  Limitation : Only this format can be parsed %S, %M, %H, %d, %m, %Y
*
* @author Lionel SAURON
* @version 1.0
* @public
*
* @param $sDate(string)    The string to parse (e.g. returned from strftime()).
* @param $sFormat(string)  The format used in date  (e.g. the same as used in strftime()).
* @return (array)          Returns an array with the <code>$sDate</code> parsed, or <code>false</code> on error.
*/
if(function_exists("strptime") == false)
{
    function
strptime($sDate, $sFormat)
    {
       
$aResult = array
        (
           
'tm_sec'   => 0,
           
'tm_min'   => 0,
           
'tm_hour'  => 0,
           
'tm_mday'  => 1,
           
'tm_mon'   => 0,
           
'tm_year'  => 0,
           
'tm_wday'  => 0,
           
'tm_yday'  => 0,
           
'unparsed' => $sDate,
        );
       
        while(
$sFormat != "")
        {
           
// ===== Search a %x element, Check the static string before the %x =====
           
$nIdxFound = strpos($sFormat, '%');
            if(
$nIdxFound === false)
            {
               
               
// There is no more format. Check the last static string.
               
$aResult['unparsed'] = ($sFormat == $sDate) ? "" : $sDate;
                break;
            }
       
        .....
        .....
        .....
        .....
       
       
// ===== Create the other value of the result array =====
       
$nParsedDateTimestamp = mktime($aResult['tm_hour'], $aResult['tm_min'], $aResult['tm_sec'],
                               
$aResult['tm_mon'] + 1, $aResult['tm_mday'], $aResult['tm_year'] + 1900);
       
       
// Before PHP 5.1 return -1 when error
       
if(($nParsedDateTimestamp === false)
        ||(
$nParsedDateTimestamp === -1)) return false;
       
       
$aResult['tm_wday'] = (int) strftime("%w", $nParsedDateTimestamp); // Days since Sunday (0-6)
       
$aResult['tm_yday'] = (strftime("%j", $nParsedDateTimestamp) - 1); // Days since January 1 (0-365)

       
return $aResult;
    }
// END of function
   
} // END if(function_exists("strptime") == false)
?>
up
0
chad 0x40 herballure 0x2e com
16 years ago
The result of strptime() is not affected by the current timezone setting, even though strftime() is. Tested in PHP 5.1.6.
up
0
DT <pwadas at gazeta dot pl>
17 years ago
<?php
//This turns non-standard but often used "datetime" string
//like '20060810084251' into nice formatted date
//'Thursday, 10 August 2006 08:42:51 CEST'
//note, that strptime returns day of year counting from 0, so
//you need to put 1 as month number to get appropriate
//month for the daycount. for 2006 strptime for unknown
//reason returns 106, so I simply add 1900

$informat = '%Y%m%d%H%M%S';
$outformat '%A, %d %B %Y %T %Z';
$ftime = strptime("20060810084251",$informat);
$unxTimestamp = mktime(
                   
$ftime['tm_hour'],
                   
$ftime['tm_min'],
                   
$ftime['tm_sec'],
                   
1 ,
                   
$ftime['tm_yday'] + 1,
                  
$ftime['tm_year'] + 1900
                
);
//setlocale(LC_TIME,'pl_PL');
echo strftime($outformat , $unxTimestamp );
?>
up
-1
firefox3107 at gmail dot com
15 years ago
For Windows user! It's rather the same as strptime!
It uses the previous function: but call strToTime($date, $format) to strToDate($date, $format) because this name is forgiven!

<?php
function strToDateTime($date, $format) {
    if(!(
$date = strToDate($date, $format))) return;
   
$dateTime = array('sec' => 0, 'min' => 0, 'hour' => 0, 'day' => 0, 'mon' => 0, 'year' => 0, 'timestamp' => 0);
    foreach(
$date as $key => $val) {
        switch(
$key) {
            case
'd':
            case
'j': $dateTime['day'] = intval($val); break;
            case
'D': $dateTime['day'] = intval(date('j', $val)); break;
           
            case
'm':
            case
'n': $dateTime['mon'] = intval($val); break;
            case
'M': $dateTime['mon'] = intval(date('n', $val)); break;
           
            case
'Y': $dateTime['year'] = intval($val); break;
            case
'y': $dateTime['year'] = intval($val)+2000; break;
           
            case
'G':
            case
'g':
            case
'H':
            case
'h': $dateTime['hour'] = intval($val); break;
           
            case
'i': $dateTime['min'] = intval($val); break;
           
            case
's': $dateTime['sec'] = intval($val); break;
        }
    }
   
$dateTime['timestamp'] = mktime($dateTime['hour'], $dateTime['min'], $dateTime['sec'], $dateTime['mon'], $dateTime['day'], $dateTime['year']);
    return
$dateTime;
}
?>
To Top