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

在DotLiquid中转换.NET格式日期为Unix时间戳的方法求助

在.NET环境的DotLiquid中转换日期为Unix时间戳

DotLiquid的Ruby实现支持用date :"%s"直接输出Unix时间戳(自1970年1月1日以来的秒数),但.NET版本的date过滤器并没有实现%s这个格式符,所以直接使用会返回0,可通过以下两种方式解决:

方式1:自定义DotLiquid过滤器

这是最可靠的方案,通过编写C#代码扩展DotLiquid的过滤器:

1. 编写过滤器类

using DotLiquid;
using System;
using System.Globalization;

public class CustomDateFilters
{
    // 将日期字符串转换为Unix时间戳(秒)
    public static long ToUnixSeconds(string dateStr)
    {
        // 指定日期格式解析,避免因系统文化差异出错
        if (DateTime.TryParseExact(dateStr, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime date))
        {
            DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            // 转换为UTC时间后计算差值
            return (long)(date.ToUniversalTime() - epoch).TotalSeconds;
        }
        return 0; // 解析失败时返回0,可按需调整
    }
}

2. 注册过滤器

在初始化DotLiquid的地方注册这个自定义过滤器:

Template.RegisterFilter(typeof(CustomDateFilters));

3. 在模板中使用

{% assign nowDate = '2022-11-20' %}
{{ nowDate | to_unix_seconds }}

执行后会得到正确结果:1668902400

方式2:模板内计算(无需编写C#代码)

如果无法添加自定义代码,可利用DotLiquid对DateTime对象的支持,通过计算日期差值实现:

{% assign epoch = '1970-01-01' | date: 'o' %}
{% assign targetDate = '2022-11-20' | date: 'o' %}
{% assign timeDiff = targetDate - epoch %}
{{ timeDiff.TotalSeconds | round }}

这里用date: 'o'确保字符串被转换为DateTime对象,再计算与epoch的时间差,最后取总秒数并取整。

关键注意点

  • Unix时间戳基于UTC时间,转换时务必确保日期时区正确,避免本地时间和UTC的偏差导致结果错误。
  • 如果你的日期格式不是yyyy-MM-dd,需要在自定义过滤器的TryParseExact中修改对应的格式字符串,保证解析准确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:45:41