当前位置: 代码迷 >> 综合 >> 相对时间格式化
  详细解决方案

相对时间格式化

热度:36   发布时间:2024-02-26 20:45:32.0

看了一篇关于相对时间格式化的文章,觉得以后可能会用上,记录一下;

原博地址:Intl.RelativeTimeFormat相对时间格式化

防止地址可能失效,还是手动敲一下

现在使用相对时间格式的地方越来越多,比如几秒前,几天前这种相对时间格式的,现在流行的几个库实现这些效果,比如Moment.js,Globalize和date-fns,现在使用原生API也可以实现这种效果。

语法:

relativeTimeFormat.format(value, unit)
value: 数值
unit:"year","month","hour","minute","second","week","day","quarter(季度)"

 用法示例:

const time = new Intl.RelativeTimeFormat('zh');time.format(2,'day'); //两天后
time.format(-2,'day'); //两天前当然英文也可以
const time = new Intl.RelativeTimeFormat('en');time.format(2,'day'); //in 2 day
time.format(-2,'day'); // 2 days ago

 

  相关解决方案