[英]php/mysql: strToTime error manipulating dates
我有一些用於渲染日期的代碼,該代碼已經運行了好幾年,現在已經壞了。 我不知道這是否與我的主機更改PHP版本有關,或者某種程度上導致了錯誤。
基本上,日期(例如11/30/15
現在呈現為11/30/15
11/30/-1
這是一個正在發生的事的例子:
$olddate = $row['date'];//in database this looks like:0000-00-00 00:00:00
$newdate = nicedate($olddate);
echo "starting date time: ".$olddate;//displays as 'starting date time: 0000-00-00 00:00:00'
echo "after transforming it with nice date: ".$newdate; //displays as 'after transforming it with nice date: 11/30/-1'
我還嘗試僅運行strtotime並獲得以下信息:
echo "after transforming it with strtotime: ".nicedate($row['starttime']);//-62169966000
// gets nice data
function nicedate($datetime) {
$niceDate = strtotime($datetime);
$niceDate = date("m/d/y",$niceDate);
return $niceDate;
}
如您在這里看到的https://3v4l.org/8gqCK,它實際上取決於您使用的PHP版本。
PHP將呈現字符串0000-00-00 00:00:00
到-0001-11-30 00:00:00.000000
這是DateTime的示例輸出:
object(DateTime)#1 (3) {
["date"]=>
string(27) "-0001-11-30 00:00:00.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Berlin"
}
輸出還取決於時區:
object(DateTime)#1 (3) {
["date"]=>
string(27) "-0001-11-29 23:06:32.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(3) "UTC"
}
這將輸出:
...約會愉快:11/29 / -1
在這里strtotime() :
int(-62169987208)
因此,您看到日期功能在不同版本上已更改,現在您可以執行的操作僅是檢查日期是否為0000-00-00 00:00:00
:
function nicedate ( $datetime ) {
if( $datetime == "0000-00-00 00:00:00" ) return "Some value or false?";
...
...
}
您還可以查看MySQL模式: NO_ZERO_IN_DATE
由於以下評論而更新了方法:
function nicedate( $datetime ) {
if( !validateDate( $datetime ) ) return "something";
$dateTimeObject = DateTime::createFromFormat('Y-m-d H:i:s', $datetime );
return $dateTimeObject->format( "m/d/y" );
}
function validateDate($date) {
$d = DateTime::createFromFormat('Y-m-d H:i:s', $date);
return $d && $d->format('Y-m-d H:i:s') == $date;
}
這是因為0000-00-00....
不是有效日期。 發生的事情很簡單,從年,月,日...開始總是減去最后一(1)。
0000 -1 = -1// year
00 - 1 = 11// month, because 12 is the highest value that datetime recognizes as month
00 - 1 = 30// day, because 31 is the highest value that datetime recognizes as day
數小時,數分鍾,數秒……都可以,因為零是時間的有效值。
這就是為什么要這樣渲染: -0001-11-30 00:00:00.000000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.