使用JavaScript(WordPress,Timber / Twig)在“活动结束日期”中添加一天

我需要在“发布日期”(WordPress)中设置的“结束日期”添加一天的时间

这是整个代码段:

document.addEventListener('DOMContentLoaded',function() {
      var calendarEl = document.getElementById('calendar');

      var calendar = new FullCalendar.Calendar(calendarEl,{
        events: [
        {% for post in events %}
        {
          title  : '{{ post.title }} | {{ post.location }}',start  : '{{ post.start_date|date('Y-m-d') }}',end    : '{{ post.end_date|date('Y-m-d') }}',color  : '{{ post.type }}'
        },{% endfor %}
        ],plugins: [ 'dayGrid' ]
      });

      calendar.render();
    });

任何人都知道如何最好地做到这一点?最好在此代码段内。

谢谢。

weiwei1988110 回答:使用JavaScript(WordPress,Timber / Twig)在“活动结束日期”中添加一天

您首先需要将时间转换为日期时间对象。为此,我将使用一个函数:

functions.php

function convert_date_to_format( $date_string,$format = 'Y-m-d' ) {
    $date = DateTimeImmutable::createFromFormat(
        'Ymd',$date_string
    );

    return $date->format( $format );
}

由于您已经知道日期字符串(Ymd)的日期格式,因此可以使用DateTimeImmutable::createFromFormat()

PHP中的datetime对象具有一种format()方法,用于以您定义的格式输出日期。

在这里,您可以使用此功能:

{% for post in events %}
    {
      title : '{{ post.title }} | {{ post.location }}',start : '{{ fn('convert_date_to_format',post.start_date,'Y-m-d') }}',end   : '{{ fn('convert_date_to_format',post.end_date,color : '{{ post.type }}'
    },{% endfor %}

现在,这实际上是extending your post的完美用例,并将您的逻辑从Twig转移到PHP。如果您有权定义post变量,则可以通过扩展Timber\Post为事件发布创建特定的类。

<?php

class EventPost extends Timber\Post {
    /**
     * Converts a date from Ymd format to another format.
     *
     * @param string $date_string The date string in Ymd format.
     * @param string $format      The desired output format.
     *
     * @return string
     */
    protected function convert_date_to_format( $date_string,$format ) {
        $date = DateTimeImmutable::createFromFormat(
            'Ymd',$date_string
        );

        return $date->format( $format );
    }

    /**
     * Gets formatted start date.
     *
     * @param string $format Optional. The preferred format. Default `Y-m-d`.
     *
     * @return string
     */
    public function start_date( $format = 'Y-m-d' ) {
        $date = $this->meta( 'start_date' );

        return $this->convert_date_to_format( $date,$format );
    }

    /**
     * Gets formatted end date.
     *
     * @param string $format Optional. The preferred format. Default `Y-m-d`.
     *
     * @return string
     */
    public function end_date( $format = 'Y-m-d' ) {
        $date = $this->meta( 'end_date' );

        return $this->convert_date_to_format( $date,$format );
    }
}

您可以像这样准备post

$context['post'] = new EventPost();

您的Twig模板将如下所示:

{% for post in events %}
    {
      title : '{{ post.title }} | {{ post.location }}',start : '{{ post.start_date('Y-m-d') }}',end   : '{{ post.end_date('Y-m-d') }}',{% endfor %}
本文链接:https://www.f2er.com/2663670.html

大家都在问