【问题标题】:How can I use a variable in a date diff function?如何在日期差异函数中使用变量?
【发布时间】:2017-08-14 17:57:52
【问题描述】:

我正在使用 ACF 字段来允许客户端内容管理他们下一个事件的倒计时我在桌面版本上使用 JS 翻转时钟,但由于它没有响应,我决定使用日期差异来回显移动天数。

该网站目前位于theindustrialproject.co.uk

我目前的代码是这样的:

<?php
    $date1 = date_create(date());
    $date2 = date_create(the_field('mobile_date'));
    $diff = date_diff($date1,$date2);

    $difference = $diff;

    if ($difference < 0) { $difference = 0; }
    echo '<span class="countdown-mobile">'. floor($difference/60/60/24)."</span><br />";
    if ($difference == 1) { echo "<p>Day</p>"; }
        else { echo "<p>Days</p>"; }
?>

但它总是返回0。作为参考,我从here中提取了代码

【问题讨论】:

  • date_diff 不返回数字,而是返回 DateInterval object。你有没有检查过$difference 在你强制它为 0 的 if 语句之前和之后的值?

标签: php wordpress advanced-custom-fields


【解决方案1】:

在不知道函数 the_field('mobile_date') 将返回什么(日期或时间戳?)的情况下,您可能需要更改下面的特定行,但您应该能够使用 DateTime 对象并像这样格式化差异

$format='Y-m-d';
$timezone=new DateTimeZone('Europe/London');

/* We need 2 datetime objects - one for now the other for the future date */
$now=new DateTime( date( $format, strtotime('now') ), $timezone );
$target=new DateTime( the_field('mobile_date'), $timezone );

/* Format the difference in days */
$days = $now->diff( $target )->days;

echo "<span class='countdown-mobile'>{$days}</span><br />" . ( $days == 1 ? '<p>Day</p>' : '<p>Days</p>' );

【讨论】:

  • 谢谢,这让我更进一步,但还不够。到 2017 年 9 月 8 日,它将返回 17392 天。我试过除以 60 和 24,以防函数返回小时或分钟,但这并不完全奏效。函数the_field('mobile_date') 从数据库中回显一个自定义字段。我已将其更改为get_field('mobile_date'),因为它只是对字段进行了排序。 mobile_date 当前设置为文本字段。
  • 请问the_field('mobile_date')的输出是什么?
  • 2017-08-17 回显到页面并复制/粘贴输出
  • 好的 - 因为在我写答案时该函数的返回值是未知的,所以 date( $format,the_field('mobile_date') ) 的使用不正确,因为它已经是一个日期 - 请参阅上面的更改。
猜你喜欢
  • 2018-09-30
  • 2013-08-23
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 2020-04-03
  • 2018-03-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多