停止使用strotime()
, date()
, time()
等功能,开始使用DateTime http://www.php.net/manual/en/book.datetime.php.
适用于所有类型已知输入的完美解决方案:
$dt = DateTime::createFromFormat('d/m/Y', $yourDMYinput);
echo $dt->getTimestamp(); # or $dt->format('U');
为什么需要时间戳?
为什么要爆炸、更换甚至剪断琴弦???只需使用创建格式 http://php.net/manual/en/datetime.createfromformat.php.
Q1:因为 PHP 5.3 以下不支持。
v5.5 已经出来了。我认为答案应该是最新的代码,而不是 2006 年的代码。是的,v5.2 于 2006 年发布,v5.3 于 2009 年发布(查看发布日期 http://en.wikipedia.org/wiki/PHP)。如果OP请求旧代码,请在SO上找到它,并以重复项结束此问题;不要回答。
Q2:因为我不知道日期时间。
学习它。
Q3:因为我可以做更多strotime()
, date()
, time()
etc.
向我展示此函数可以做而 DateTime 不能做的一件事。
“已弃用”代码示例:
$input = '12/09/2013'; # dd/mm/yyyy
$new = substr($input,6,4)."-".substr($input,3,2)."-".substr($input,0,2);
$new = strtotime($new);
echo "$new\n";
$m = explode('/', $input);
$new = mktime(0,0,0,$m[1],$m[0],$m[2]);
echo "$new\n";
$new = str_replace("/", "-", $input);
$new = strtotime($new);
echo "$new\n";
preg_match('~^(\d+)/(\d+)/(\d+)$~', $input, $m);
$new = strtotime("$m[3]-$m[2]-$m[1]");
echo "$new\n";
$m = sscanf($input, '%d/%d/%d');
$new = strtotime("$m[2]-$m[1]-$m[0]");
echo "$new\n";
如果您有另一个已弃用代码的示例,请编辑此答案并添加它;)