You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Liquid模板中使用date函数获取相对当前日期的过去/未来日期

在CucumberJS测试的Liquid模板中实现相对日期计算

你目前已经能通过Liquid的now过滤器获取当前系统日期:

"{{ "now" | date: "%Y%m%d" }}", "{{ "now" | date: "%Y%m%d" }}"

要生成相对于当前日期的过去或未来日期,由于Liquid默认没有内置的日期偏移功能,你可以通过自定义Liquid过滤器来实现,具体步骤如下:

1. 注册自定义日期偏移过滤器

在CucumberJS的测试初始化代码中,给Liquid引擎注册一个自定义过滤器,用于计算日期偏移:

const { Liquid } = require('liquidjs');

// 初始化Liquid实例
const liquidEngine = new Liquid();

// 注册自定义过滤器:接收天数偏移量,返回格式化后的日期字符串
liquidEngine.registerFilter('relativeDate', function(daysOffset) {
  const currentDate = new Date();
  // 计算偏移后的日期:正数为未来,负数为过去
  currentDate.setDate(currentDate.getDate() + daysOffset);
  // 格式化为YYYYMMDD格式
  return currentDate.toISOString().slice(0, 10).replace(/-/g, '');
});

2. 在Liquid模板中使用自定义过滤器

直接在模板里调用relativeDate过滤器,传入偏移天数即可:

// 昨天的日期
"{{ -1 | relativeDate }}",
// 明天的日期
"{{ 1 | relativeDate }}",
// 3天后的日期
"{{ 3 | relativeDate }}",
// 7天前的日期
"{{ -7 | relativeDate }}"

如果需要保留原有的date过滤器灵活性(比如切换日期格式),也可以调整过滤器逻辑,让它先处理日期偏移,再交给date过滤器格式化:

liquidEngine.registerFilter('dateOffset', function(baseDate, daysOffset) {
  const targetDate = baseDate === 'now' ? new Date() : new Date(baseDate);
  targetDate.setDate(targetDate.getDate() + daysOffset);
  return targetDate;
});

模板写法:

"{{ "now" | dateOffset: -1 | date: "%Y%m%d" }}", "{{ "now" | dateOffset: 5 | date: "%Y%m%d" }}"

3. 集成到CucumberJS测试流程

确保在加载和渲染Liquid模板之前,已经完成自定义过滤器的注册,这样测试运行时模板就能正确解析并生成所需的相对日期。

内容的提问来源于stack exchange,提问作者SymboCoder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 20:45:13