php 如何从php中的日期时间戳获取时间和日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9904080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get time and Date from datetime stamp in php
提问by user1153176
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
我有 1 个字符串,就像8/29/2011 11:16:12 AM
我想保存在变量中一样 $dat = 8/29/2011 和 $tme = 11:16:12 AM
how would is possible? can you give me example?
怎么可能?你能给我举个例子吗?
回答by VolkerK
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
见http://docs.php.net/class.datetime
edit: To keep the AM/PM format use
编辑:要保持 AM/PM 格式使用
$time = $dt->format('h:i:s A');
回答by user1297515
You could use the strtotime function, as long as the dates are after 1/1/1970 -
您可以使用 strtotime 函数,只要日期在 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
http://php.net/manual/en/function.strtotime.php
strtotime creates a UNIX timestamp from the string you pass to it.
strtotime 根据您传递给它的字符串创建一个 UNIX 时间戳。
回答by Tuong Le
<?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
有关 date() 函数的更多信息,请访问http://php.net/manual/en/function.date.php
回答by haltabush
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];
回答by JTeagle
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.
如果您的 PHP 版本足够新,请查看 date_parse() 及其返回的数组。然后您可以使用相关条目格式化日期或时间部分。
回答by Jovan Perovic
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...
现在,$date
并$time
具有适当的值...
回答by Msmit1993
Yes this is possible, and the perfect example can be found here http://php.net/manual/en/function.date.php
是的,这是可能的,完美的例子可以在这里找到http://php.net/manual/en/function.date.php
Good luck,
祝你好运,