If you are just looking to switch an existing time format into a mysql compatible format(like YYYYMMDDHHMMSS.uuuuuu) you should use STR_TO_DATE.
see: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html
However, if you have an old version of mysql (before 4.1), you may want to consider using a regex. The example below doesnt have seconds because they arent used often if you are ripping data from a web page. You will probably have to customize this to your needs.
==code== // for 24 hour times
<?php
$before = "12/15/2005 15:47";
$after = preg_replace("/([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})/", "$3$1$2$4$5", $before)."00.000000";
echo "$before\n$after\n";
?>
==output==
12/15/2005 15:47
20051215154700.000000
.
If you are unlucky, you will need to be converting to the 24 hour format as well.
==code== // for 12 hour AM/PM times
<?php
$before = "12/15/2005 03:47PM";
// note: you can use an anonymous function instead IF you have php 5
function convert_time($m) { if($m[6]=="PM") { $m[4]+=12; } return $m[3].$m[1].$m[2].$m[4].$m[5]."00.000000"; }
$after = preg_replace_callback("/([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})(AM|PM)/", "convert_time", $before);
echo "$before\n$after\n";
?>
==output==
12/15/2005 03:47PM
20051215154700.000000
説明
array strptime
( string $date
, string $format
)
strptime() は date をパースした結果を配列で返します。エラー時には FALSE を返します。
月名や曜日、そしてその他の言語依存な文字列は setlocale() (LC_TIME) で設定された現在の ロケールを考慮して返します。
パラメータ
- date (string)
-
パースする文字列(例: strftime() の返り値)。
- format (string)
-
date で使用されているフォーマット (例: strftime() で使用されていたものと同じ)。
フォーマットオプションについての詳細は strftime() のページを参照ください。
返り値
成功した場合は配列、失敗した場合は FALSE を返します。
| パラメータ | 説明 |
|---|---|
| "tm_sec" | 分未満の秒数 (0-61) |
| "tm_min" | 時間未満の分数 (0-59) |
| "tm_hour" | 0 時以降の時間数 (0-23) |
| "tm_mday" | 月内の日数 (1-31) |
| "tm_mon" | 1 月から数えた月数 (0-11) |
| "tm_year" | 1900 年以降の年 |
| "tm_wday" | 日曜日からの日数 (0-6) |
| "tm_yday" | 1 月 1 日からの日数 (0-365) |
| "unparsed" | date の中で、指定された format で判断できなかった部分 |
例
例1 strptime() の例
<?php
$format = '%d/%m/%Y %H:%M:%S';
$strf = strftime($format);
echo "$strf\n";
print_r(strptime($strf, $format));
?>
上の例の出力は、 たとえば以下のようになります。
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] =>
)
注意
注意: この関数は Windows 環境にはまだ実装されていません。
注意: "tm_sec" には、うるう秒も組み込まれています (現在は、年間 2 秒まで)。うるう秒についての詳細な情報は » Wikipedia の記事 を参照ください。
strptime
Gravis
03-Apr-2009 10:33
03-Apr-2009 10:33
Quietust
28-Feb-2009 01:38
28-Feb-2009 01:38
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.
Altar 2010
24-Oct-2008 05:45
24-Oct-2008 05:45
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)
?>
firefox3107 at gmail dot com
24-Mar-2008 11:44
24-Mar-2008 11: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;
}
?>
P.
30-Jan-2008 09:19
30-Jan-2008 09: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 11:00
15-Jun-2007 11: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 06:44
23-Nov-2006 06: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>
11-Aug-2006 04:55
11-Aug-2006 04:55
<?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 );
?>
jojyjob at gmail dot com
13-May-2006 04:18
13-May-2006 04: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
28-Mar-2006 03:45
28-Mar-2006 03: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().
