【问题标题】:Displaying time relative to a given using luxon library使用 luxon 库显示相对于给定时间的时间
【发布时间】:2019-05-11 19:57:25
【问题描述】:

luxon 是否支持显示相对于给定时间的功能?

Moment 有“日历时间”功能:

https://momentjs.com/docs/#/displaying/calendar-time/

moment().calendar(null, {
   sameDay: '[Today]',
   nextDay: '[Tomorrow]',
   nextWeek: 'dddd',
   lastDay: '[Yesterday]',
   lastWeek: '[Last] dddd',
   sameElse: 'DD/MM/YYYY'
});

我可以使用 luxon 达到同样的效果吗?

【问题讨论】:

    标签: luxon


    【解决方案1】:

    1.9.0 版本开始,您可以使用toRelativeCalendar

    返回此日期相对于今天的字符串表示,例如“昨天”或“下个月”平台支持Intl.RelativeDateFormat

    const DateTime = luxon.DateTime;
    
    const now = DateTime.local();
    // Some test values
    [ now,
      now.plus({days: 1}),
      now.plus({days: 4}),
      now.minus({days: 1}),
      now.minus({days: 4}),
      now.minus({days: 20}),
    ].forEach((k) => {
      console.log( k.toRelativeCalendar() );
    });
    <script src="https://cdn.jsdelivr.net/npm/luxon@1.10.0/build/global/luxon.js"></script>

    1.9.0 版本之前,Luxon 中没有 calendar() 等效项。

    For Moment users 手册页中说明的 DateTime 方法等效 => 输出 => Humanization 部分:

    Luxon 不支持这些,并且直到 Relative Time Format 提案登陆浏览器后才会支持。

    Operation       | Moment     | Luxon
    ---------------------------------------------------------------------------------------
    "Calendar time" | calendar() | None (before 1.9.0) / toRelativeCalendar() (after 1.9.0)
    

    如果你需要,你可以自己写一些东西,这里有一个自定义函数的例子,输出类似moment的calendar()

    const DateTime = luxon.DateTime;
    
    function getCalendarFormat(myDateTime, now) {
      var diff = myDateTime.diff(now.startOf("day"), 'days').as('days');
      return diff < -6 ? 'sameElse' :
        diff < -1 ? 'lastWeek' :
        diff < 0 ? 'lastDay' :
        diff < 1 ? 'sameDay' :
        diff < 2 ? 'nextDay' :
        diff < 7 ? 'nextWeek' : 'sameElse';
    }
    
    function myCalendar(dt1, dt2, obj){
      const format = getCalendarFormat(dt1, dt2) || 'sameElse';
      return dt1.toFormat(obj[format]);
    }
    
    const now = DateTime.local();
    const fmtObj = {
       sameDay: "'Today'",
       nextDay: "'Tomorrow'",
       nextWeek: 'EEEE',
       lastDay: "'Yesterday'",
       lastWeek: "'Last' EEEE",
       sameElse: 'dd/MM/yyyy'
    };
    
    // Some test values
    [ now,
      now.plus({days: 1}),
      now.plus({days: 4}),
      now.minus({days: 1}),
      now.minus({days: 4}),
      now.minus({days: 20}),
    ].forEach((k) => {
      console.log( myCalendar(now, k, fmtObj) );
    });
    &lt;script src="https://cdn.jsdelivr.net/npm/luxon@1.8.2/build/global/luxon.js"&gt;&lt;/script&gt;

    这段代码大致灵感来自时刻code,绝对可以改进。

    【讨论】:

    • 小记:我想我们应该使用 now.startOf("day") 而不是 now 在函数 getCalendarFormat。
    • @ilyabasiuk 你说得对,我已经修复了 sn-p 中的代码。
    • 有没有办法通过组装字符串或注入格式来定制特定时间差异的选择?就我而言,我更喜欢“上周一”或任何更早的日期,而不是“4 天前”,而不是“20 天前”。
    猜你喜欢
    • 2020-06-08
    • 1970-01-01
    • 2021-07-28
    • 2022-08-19
    • 2021-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多