PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

strtotime> <strftime
Last updated: Fri, 11 Apr 2008

view this page in

strptime

(PHP 5 >= 5.1.0)

strptime — Manipula la hora/fecha obtenida mediante strftime()

Descripción

array strptime ( string $marca_de_tiempo , string $formato )

strptime() devuelve una matriz que contiene el valor marca_de_tiempo manipulado según el formato o FALSE si se ha producido un error.

Los nombres de los meses y de los días de la semana y otras cadenas dependientes del idioma, siguen la configuración de localización actual, establecida con setlocale() (LC_TIME).

Lista de parámetros

marca_de_tiempo (string)

Una marca de tiempo (igual que la devuelta por strftime())

formato (string)

El formato usado en formato (igual que el usado en strftime()).

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

Valores retornados

Devuelve una matriz o FALSE si se produce un error.

La matriz devuelta contiene los siguientes parámetros
Parámetros Descripción
tm_sec Segundos transcurridos del minuto actual (0-61)
tm_min Minutos transcurridos de la hora actual (0-59)
tm_hour Horas transcurridas desde la media noche (0-23)
tm_mday Día del mes (1-31)
tm_mon Meses transcurridos desde Enero (0-11)
tm_year Años transcurridos desde 1900
tm_wday Días transcurridos desde el Domingo (0-6)
tm_yday Días transcurridos desde el 1 de Enero (0-365)
unparsed La parte de la marca_de_tiempo que no se pudo reconocer empleando el parámetro formato

Ejemplos

Example #1 Ejemplo de strptime()

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

echo 
"$fecha_formateada\n";

print_r(strptime($fecha_formateada$formato));
?>

El resultado del ejemplo seria 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] =>
)

Ver también

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



strtotime> <strftime
Last updated: Fri, 11 Apr 2008
 
add a note add a note User Contributed Notes
strptime
firefox3107 at gmail dot com
24-Mar-2008 03:44
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;
}
?>
firefox3107 at gmail dot com
06-Mar-2008 08:01
It's not the same as strptime. The array keys are different, for example '%d' will produce 'd' => '12'!!!
But it also returns false on failure.

<?php

function strToTime($date, $format) {
   
$search = array('%d', '%D', '%j', // day
                   
'%m', '%M', '%n', // month
                   
'%Y', '%y', // year
                   
'%G', '%g', '%H', '%h', // hour
                   
'%i', '%s');
   
$replace = array('(\d{2})', '(\w{3})', '(\d{1,2})', //day
                    
'(\d{2})', '(\w{3})', '(\d{1,2})', // month
                    
'(\d{4})', '(\d{2})', // year
                    
'(\d{1,2})', '(\d{1,2})', '\d{2}', '\d{2}', // hour
                    
'(\d{2})', '(\d{2})');
   
   
$pattern = str_replace($search, $replace, $format);
   
    if(!
preg_match("#$pattern#", $date, $matches)) {
        return
false;
    }
   
$dp = $matches;
   
    if(!
preg_match_all('#%(\w)#', $format, $matches)) {
        return
false;
    }
   
$id = $matches['1'];

    if(
count($dp) != count($id)+1) {
        return
false;
    }

   
$ret = array();
    for(
$i=0, $j=count($id); $i<$j; $i++) {
       
$ret[$id[$i]] = $dp[$i+1];
    }

    return
$ret;
}
?>
ubik.dr at gmail.com
01-Mar-2008 06:27
fields of the returned struct referring to unspecified parts of the message are filled strangely:

print_r(strptime('19841203', '%Y%m%d'));

Array
(
    [tm_sec] => 142611740
    [tm_min] => 12
    [tm_hour] => -1074490616
    [tm_mday] => 3
    [tm_mon] => 11
    [tm_year] => 84
    [tm_wday] => 1
    [tm_yday] => 337
    [unparsed] =>
)
P.
30-Jan-2008 01:19
If strptime() fails to match all of the format string and therefore an error occurred the function returns NULL.
chad 0x40 herballure 0x2e com
15-Jun-2007 04:00
The result of strptime() is not affected by the current timezone setting, even though strftime() is. Tested in PHP 5.1.6.
svenr at selfhtml dot org
23-Nov-2006 10:44
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
DT <pwadas at gazeta dot pl>
10-Aug-2006 09:55
//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 );
jojyjob at gmail dot com
13-May-2006 09:18
/***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;
}

?>
Malte Starostik
27-Mar-2006 08:45
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().

strtotime> <strftime
Last updated: Fri, 11 Apr 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites