如何从PHP中的日期时间戳获取时间和日期
i have 1 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 would is possible? can you give me example?
我有1个字符串,如 怎么可能? 你能举个例子吗? p>
div> 8/29/2011 11:16:12 AM code> i 想要保存在$ dat = 8/29/2011和$ tme = 11:16:12 AM之类的变量中 p>
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');
This should do the trick:
$mystring_datetime = ....;
$dt = DateTime::createFromFormat('m/d/Y H:i:s A', $mystring_datetime );
$d = $dt->format('m/d/Y');
$t = $dt->format('H:i:s A');
You could also do something like this but it's not preferred way:
$mystring_datetime = ....;
list($date, $time) = explode(' ', $mystring_datetime, 2);
Now, $date
and $time
have appropriate values...
If your version of PHP is new enough, check out date_parse() and the array it returns. You can then format date or time portions using the relevant entries.
This is probably not the cleanest way of doing it, but you can use an explode (note that there is NO validation at all here). It will be faster than a proper date manipulation.
$str = '8/29/2011 11:16:12 AM';
$dates = explode(' ', $str);
$dat = $dates[0];
$time = $dates[1];
Yes this is possible, and the perfect example can be found here http://php.net/manual/en/function.date.php
Good luck,
<?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
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.