PHP transforming time formats and adding random time vars

对着背影说爱祢 提交于 2019-12-11 02:21:55

问题


I need to generate a time of format : [ Y-m-d H:i:s ] from strings that look like 7/03/2013 ( yep, can be 7 or 07 ) .

I use

$date = '7/03/2013';
$date = date('Y-m-d H:i:s', strtotime($date));

This works just fine . So where is the problem ?

The problem is that I do not have the H:i:s part, but I need it in order to insert to DB.

So I just tried to random it :

$rand = rand(00,24); 
$datenew = date('Y-m-d '.$rand.':i:s', strtotime($date));

but that produces time like 4 or 6 where i need 04 and 06 so :

$rand = rand(0,2) . rand(1,4) ;
$datenew = date('Y-m-d '.$rand.':'.$rand.':s', strtotime($date));

But that just seems to me articulately non elegant .

I also need the minutes , so I need somehow to format rand(00,60) ;

but combining that can create also unrealistic times like 24:26:00

So how can I take the time I have with format 7/03/2013 , transform to H:i:s and add random hour , minutes (and maybe sec.)


回答1:


$dt = DateTime::createFromFormat('n/d/Y', '7/03/2013');
echo $dt->format('Y-m-d H:i:s');

See it in action

The times will vary depending on when you run the code.




回答2:


You could use Y-m-d 00:00:00 instead. Or, if you need it to be random, you could use something like:

date('Y-m-d ' . sprintf('%02d:%02d:00', mt_rand(0, 23), mt_rand(0, 59)));



回答3:


This would produce a random number for HH:ii:ss

$date = '7/03/2013';

$new_date  = date('Y-m-d', strtotime($date));
$new_date .= date(' H:i:s', mt_rand(0,1262055681));


来源:https://stackoverflow.com/questions/15683739/php-transforming-time-formats-and-adding-random-time-vars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!