我知道php strtotime()函数并不是所有日期时间格式的答案。但是,我在下面描述的这种行为真的很危险,因为它会让你相信它确实在工作时确实不是:
用户告诉我她正在从下拉菜单中输入日期格式。我在字符串中获取该日期,并在其上运行strtotime()。通常情况下效果很好,但这里有陷阱:
//year 1999
$timedate = "1999"; //string from the form marked as datetime
$utime = strtotime($timedate); //Unixtime format
// Now check the results .. they are correct
echo "Raw TimeDate = $timedate. After calling strtotime() it is ".$utime." UnixTimeStamp or ". date( "Y-m-d : H:i:s", $utime)."<br/>";
//year 2000
$timedate = "2000";
$utime = strtotime($timedate); //WRONG ANSWER!!!!
echo "Raw TimeDate = $timedate. After calling strtotime() it is ".$utime." UnixTimeStamp or ". date("Y-m-d : H:i:s",$utime)."<br/>";
当给予strtotime的数字不明确时会发生这种情况。 strtotime()往往只将其解析为TIME(20小时00分钟)而不是2000年DATE,这与字符串“1999”相反 这里毫无疑问,这只是一个Be Aware注释
答案 0 :(得分:1)
这就是使用PHP - DateTime
的原因例如:
//year 2000
$timedate = "2000";
$date = date_create_from_format('Y', $timedate);
echo "Raw TimeDate = $timedate. After calling strtotime() it is ".$utime." UnixTimeStamp or ". date("Y-m-d : H:i:s",$date->getTimestamp())."<br/>";
输出
Raw TimeDate = 2000.调用strtotime()后,它是930251446 UnixTimeStamp或2000-06-24:19:10:46