将日期dd / mm / yyyy格式从表单转换为时间戳? [英] convert date dd/mm/yyyy format from a form to timestamp?

查看:758
本文介绍了将日期dd / mm / yyyy格式从表单转换为时间戳?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格需要日期在 dd / mm / yyyy 格式
,我已经尝试将其转换为时间戳与 strtotime()函数

I have a form requiring date in dd/mm/yyyy format and I've tried to convert it to a timestamp with strtotime() function

但是我看到它只有在您填写表单时,如 dd-mm-yyyy

but I've seen it works only if you fill the form with date written like dd-mm-yyyy

我该如何解决?我不在国外,但在意大利这里没有人写这样的日期 dd-mm-yyyy

how could i solve? I don't know abroad but here in Italy nobody writes dates like that dd-mm-yyyy

推荐答案

停止使用 strotime() date() time()等功能,开始使用 DateTime



所有类型的已知输入的完美解决方案:

Stop using strotime(), date(), time() etc. functions, start using DateTime.

Perfect solution for all types of known input :

$dt = DateTime::createFromFormat('d/m/Y', $yourDMYinput);
echo $dt->getTimestamp(); # or $dt->format('U');

为什么需要时间戳?


Q1:因为它不支持在PHP 5.3之下。

Q1: Because its not supported below PHP 5.3.

已经有v5.5出来我认为答案应该是最新的代码,而不是2006年的代码。是的,v5.2是在2006年发布的,2009年是v5.3(查看发布日期)。如果OP请求旧代码,请在SO上找到它,并用重复关闭此问题;不要回答。

There is v5.5 already out. I think answers should be for the latest code, not for code from the year 2006. Yes v5.2 was released in 2006 and v5.3 in 2009 (see release dates). If OP requests old code, find it on SO, and close this question with duplicate; don't answer it.


Q2:因为我不知道DateTime。

Q2: Because I don't know DateTime.

了解它。


Q3: strong>因为我可以使用 strotime() date() time )等。

向我显示这个功能可以做的一件事,而DateTime不能。 >

已弃用代码示例:



Show me one thing that this functions can do, and DateTime cannot.

$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";

如果您有另一个已弃用代码的示例,请编辑此答案并将其添加;)

这篇关于将日期dd / mm / yyyy格式从表单转换为时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆