I have one string like 8/29/2011 11:16:12 AM
. I want to save in variable like $dat = '8/29/2011'
and $tme = '11:16:12 AM'
How to achieve that? Can you give me example?
Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.
$date = date("yyyy-mm-dd", strtotime(now));
PHP Date/Time IntroductionThe date/time functions allow you to get the date and time from the server where your PHP script runs. You can then use the date/time functions to format the date and time in several ways. Note: These functions depend on the locale settings of your server.
E.g.
<?php
$s = '8/29/2011 11:16:12 AM';
$dt = new DateTime($s);
$date = $dt->format('m/d/Y');
$time = $dt->format('H:i:s');
echo $date, ' | ', $time;
see http://docs.php.net/class.datetime
edit: To keep the AM/PM format use
$time = $dt->format('h:i:s A');
You could use the strtotime function, as long as the dates are after 1/1/1970 -
<?php
$s = strtotime('8/29/2011 11:16:12 AM');
$date = date('m/d/Y', $s);
$time = date('H:i:s A', $s);
?>
http://php.net/manual/en/function.strtotime.php
strtotime creates a UNIX timestamp from the string you pass to it.
<?php
$date = strtotime('8/29/2011 11:16:12 AM');
$dat = date('m/d/y', $date);
$tme = date('H:m:s A',$date);
?>
For more information about date() function, plz visit http://php.net/manual/en/function.date.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With