获取 Jekyll 中两个日期之间的天数差异

Get the difference in days between two dates in Jekyll

我想获得 Jekyll 中两个日期之间的天数差异。我怎样才能做到这一点?

{% capture currentDate %}{{ site.time | date: '%Y-%m-%d' }}{% endcapture %}
{{currentDate}}
{% capture event_date %}{{ entry.date }}{% endcapture %}
{% if event_date < currentDate %}Yes{% else %}No{% endif %}

条目中有我的 YAML:

---
title: ChartLine C3
type: charts
description: Chart with round for prisma
id: c3-1
date: 2015-07-18
--- 

如果您只想知道 Front Matter 中的日期是否早于系统时间,那么您可以使用 ISO 8601 日期格式并依赖字典顺序。这有点作弊,但它适用于您提供的示例。

重要的是从您的 Front Matter(下例中的 page.past_datepage.future_date)中捕获 site.time 和日期ISO 8601 格式才能使这个技巧起作用。

---
layout: default
past_date: 2015-03-02
future_date: 2016-03-02
---

{% capture currentDate %}{{ site.time | date: '%F' }}{% endcapture %}
{% capture pastDate %}{{ page.past_date | date: '%F' }}{% endcapture %}
{% capture futureDate %}{{ page.future_date | date: '%F' }}{% endcapture %}
<br>currentDate: {{currentDate}}
<br>PastDate earlier than currentDate? {% if pastDate < currentDate %}Yes{% else %}No{% endif %}
<br>FutureDate earlier than currentDate? {% if futureDate < currentDate %}Yes{% else %}No{% endif %}

给我以下输出:

currentDate: 2015-07-12

PastDate earlier than currentDate? Yes

FutureDate earlier than currentDate? No

No-one确实回答了问题,但也不是不可能。

你可以得到年份之间的差异,假设自 2000 年以来已经过去了多少年:

{{ site.time | date: '%Y' | minus:2000 }}

至于两个日期之间的天数,那就更难了。最好的办法是查看插件: https://github.com/markets/jekyll-timeago

它的输出可能有点冗长,但你可以修改插件本身(看看代码,它不太复杂)

在 Liquid(Jekyll 的模板引擎)中执行此操作的方法很愚蠢:

{%   assign today = site.time | date: '%s'      %}
{%   assign start = '20-01-2014 04:00:00' | date: '%s'  %}
{%   assign secondsSince = today | minus: start     %}
{%   assign hoursSince = secondsSince | divided_by: 60 | divided_by: 60     %}
{%   assign daysSince = hoursSince | divided_by: 24  %}

Hours: {{hoursSince}}
Days: {{daysSince}}

Hours: 27780

Days: 1157

请注意,Liquid 的 divide_by 操作会自动循环。

Remainder hours: {{hoursSince | modulo: 24}}

Remainder hours: 12

如果这让你和我一样烦恼,那么你可以这样做来恢复小数位:

{%   assign k = 10   %}
{%   assign divisor = 24   %}
{%   assign modulus = hoursSince | modulo: 24 | times: k | divided_by: divisor  %}
{{daysSince}}.{{modulus}}

1157.5

k 添加更多零以添加更多小数位。

我计算了当前日期与 post 日期之间的年差以呈现特定消息,并且效果很好:

{% assign currentYear = site.time | date: '%Y' %}
{% assign postYear = post.date | date: '%Y' %}
{% assign postAge = currentYear | minus: postYear | minus: 1 %}

{% if postAge >= 3 %}
<div class="maybe-obsolete">
  This post has been published more than {{ postAge }} years ago, and parts
  of its contents are very likely to be obsolete by now.
</div>
{% endif %}