2015-09-25 34 views
0

我需要从今天获得随机时间。我试过用这个使用今天的日期获取随机时间

$today = date('YmdHi'); 
$startDate = date('YmdHi', strtotime('-0.5 days')); 
$range = $today - $startDate; 
$rand = rand(0, $range); 
$smthing=$startDate + $rand; 

return $smthing; 

但它不能正常工作。

例如,我想生成今天的日期和任何它。

预期输出

2015:25:09 14点10分20秒

2015:25:09 8时12分26秒

2015:25:09 01:02 :24

+3

为什么你不能只使用'time()'。毕竟它一直都在变化! :D – jitendrapurohit

+0

@JitendraPurohit不错的一个!笑笑 – RiggsFolly

+0

这可能有助于[链接](http://stackoverflow.com/questions/1972712/generate-random-date-between-two-dates-using-php) –

回答

3

使用

$date=date('Y:m:d'); 
$sttime=strtotime($date.' '.'00:00:01'); 
$entime=strtotime($date.' '.'23:59:59'); 
$rand=rand($sttime,$entime); 
echo $rand_time=date('Y:m:d H:i:s',$rand); 

根据你的问题,它会产生当天之间的时间间隔只有

+0

伟大的作品! –

+3

考虑使用mt_rand而不是rand(); http://php.net/manual/en/function.mt-rand.php它基本上更随机和更快一点。 – gries

+0

谢谢!另外我把$ date = date('Y:m:d');而不是23:59:59。现在我在00:00:00和当前时间之间获得随机时间:) 再次感谢您! – LoverBugs

相关问题