使用strtotime格式化日期()与AM / PM

时间:2014-05-28 19:51:48

标签: php date strtotime

我编写了这行代码,用于在我的联系我们页面上的电子邮件中创建格式化的时间戳。

它工作正常,但我想知道它是否写得不好而且可以简化为更高效的代码?在一行中调用date()三次是错误的。我不是贸易开发商。

$timestamp = date('m-d-Y')." ".date('h:i A', strtotime(date('H:i:s')));

导致:05-28-2014 03:49 PM

思想?

2 个答案:

答案 0 :(得分:2)

当您需要当前时间戳时,您可以使用

$timestamp=date("m-d-Y h:i A");

如果需要格式化从数据库或其他方式获取的时间戳,则必须使用strtotime

$format_timestamp=date("Y-m-d H:i:s", strtotime($timestamp)); // I just convert your format to YYYY-MM-DD HH:MM:SS format.

编辑:

如果您需要从当前时间减去x小时,请使用

$timestamp=date("m-d-Y h:i A", strtotime("-4 hour"));

更多例子,

$timestamp=date("m-d-Y h:i A", strtotime("+2 hour")); // Adds 2 hours
$timestamp=date("m-d-Y h:i A", strtotime("+1 day")); // Adds 1 Day

答案 1 :(得分:0)

您可以简化制作:

$timestamp = date('m-d-Y h:i A');

$timestamp = gmdate("M d Y H:i:s");

有关详细信息,请参阅:

PHP手册

日期http://www.php.net/manual/en/function.date.php

gmdate http://www.php.net/manual/en/function.gmdate.php

相关问题