【问题标题】:Using strtotime to format date() with AM/PM使用 strtotime 以 AM/PM 格式化 date()
【发布时间】:2014-05-28 19:51:48
【问题描述】:

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

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

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

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

想法?

【问题讨论】:

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

标签: php date strtotime


【解决方案1】:

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

$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

【讨论】:

  • 看来我在原来的问题中遗漏了一些有价值的信息:我的实际代码如下:$timestamp = date('m-d-Y')." ".date('h:i A ', strtotime(date('H:i:s')) - 60*60*4);在格式化之前从时间(时区转换)中减去 4 小时。你会如何让这变得更好?谢谢。
  • @user3685142 时区不用手动转换,可以看看这个php.net/manual/en/function.date-default-timezone-set.php#109321
  • 感谢您的回答。顺便说一句,我必须在 -4 小时左右加上引号才能使其工作 IE:strtotime("-4 hour")
  • @user3685142:这是一个粗心的错误。虽已更正。谢谢!
【解决方案2】:

您可以简化制作:

$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

【讨论】:

    猜你喜欢
    • 2013-08-19
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    • 2016-09-15
    相关资源
    最近更新 更多