date()格式,d-m-Y和d/m/Y之间的差异 [英] date() format, differences between d-m-Y and d/m/Y
问题描述
这是我的第一篇文章,对不起,如果我做错了.好吧,我得到了这段代码
this is my first post so sorry if i do something wrong. Well I got this code
$min=date('d-m-Y');
$max=date ('31-12-2015');
function rand_date($min, $max) {
$min_epoch = strtotime($min);
$max_epoch = strtotime($max);
$rand_epoch = rand($min_epoch, $max_epoch);
return date('d-m-Y H:i:s', $rand_epoch);
}
echo rand_date($min, $max);//return 04-12-2015 07:48:22`
它可以工作,但是当我将其与我需要的格式(d/m/Y)一起使用时,问题就来了
It works, but the problem comes when I use this with the format than i need (d/m/Y)
$min=date('d/m/Y');
$max=date ('31/12/2015');
function rand_date($min, $max) {
$min_epoch = strtotime($min);
$max_epoch = strtotime($max);
$rand_epoch = rand($min_epoch, $max_epoch);
return date('d/m/Y H:i:s', $rand_epoch);
}
echo rand_date($min, $max);// Always shows 01/01/1970 01:00:00`.
我需要使用这种格式,所以如果有人回答我的问题,我将不胜感激.
I need works with this format, so I will be grateful if somebody answer my question.
推荐答案
PHP日期/时间函数/方法的 31/12/2015
的默认解释为 m/d/Y
(使用正斜杠)和 dmY
或 Ymd
(如果使用破折号),如果您
The default interpretation of 31/12/2015
for PHP date/time functions/methods is m/d/Y
when using forward-slashes, and d-m-Y
or Y-m-d
when using dashes, if you check the manual. Which is why something like date('31/12/2015')
returns false
since there is no 31st month in a year.
使用 DateTime :: createFromFormat
来指定您自己的变体你必须.
Use DateTime::createFromFormat
instead to specify your own variations if you must.
$min = new DateTime;
$max = DateTime::createFromFormat('d/m/Y', '31/12/2015');
function rand_date(DateTime $min, DateTime $max) {
$min_epoch = $min->getTimeStamp();
$max_epoch = $max->getTimeStamp();
$rand_epoch = rand($min_epoch, $max_epoch);
return (new DateTime("@$rand_epoch"))->format('d/m/Y H:i:s');
}
这篇关于date()格式,d-m-Y和d/m/Y之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!