【问题标题】:How to get relative time from a UTC date using Luxon?如何使用 Luxon 从 UTC 日期获取相对时间?
【发布时间】:2020-06-08 09:01:56
【问题描述】:

我使用我的 .net 核心 api 将帖子的创建日期存储为 DateTime.UtcNow()。

如果我使用 Moment.js,它就像这样简单:

convertedDate(date: Date) {
    return moment.utc(date).fromNow();
}

这会返回 22 小时前或 19 分钟前的内容。

我无法真正找到有关如何使用 luxon 库的信息。

有什么建议吗?

【问题讨论】:

  • 你是问如何使用 Luxon 库还是其他?
  • 最好如何使用Luxon库实现相同的方法。 @AbuSufian
  • 在 Luxon 中,您必须使用 'toRelative()' 而不是 'fromNow()'。您可以浏览此文档:github.com/moment/luxon/blob/master/docs/moment.md

标签: javascript typescript momentjs luxon


【解决方案1】:

看起来 Luxon 不支持这种行为,因为它无法访问国际化字符串。可以在此处找到更多信息/替代方案。

https://github.com/moment/luxon/issues/364

【讨论】:

    【解决方案2】:

    首先包含库或安装,说喜欢

    <script src="https://cdn.jsdelivr.net/npm/luxon@1.10.0/build/global/luxon.js"></script>
    

    然后使用以下格式获得正确的输出:

    const DateTime = luxon.DateTime;
    console.log(DateTime.local().plus({ days: 1 }).toRelative()); // in 23 hours
    console.log(DateTime.local().minus({ days: 2 }).toRelative({ unit: "hours" })); //48 hours ago
    console.log(DateTime.local().toObject()); // year: 2020 month: 2 day: 25 hour: 0 minute: 4 second: 20 millisecond: 764
    console.log(DateTime.local(2014, 7, 13).toSQL({ includeZone: true })); // 2014-07-13 00:00:00.000 Asia/Dhaka
    

    此外,如果您想探索更多以了解其他方法,请阅读 Luxon 的文档。

    https://moment.github.io/luxon/index.html
    

    【讨论】:

      【解决方案3】:

      您可以使用toRelative() luxon 函数,它的工作方式相同。例如:

      DateTime.local().minus({ days: 2 }).toRelative() //=> "2 days ago"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-06-02
        • 2021-01-11
        • 1970-01-01
        • 1970-01-01
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多