Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP transforming time formats and adding random time vars

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.)

like image 942
Obmerk Kronen Avatar asked Sep 27 '26 00:09

Obmerk Kronen


1 Answers

$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.

like image 144
John Conde Avatar answered Sep 28 '26 14:09

John Conde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!