1.0.2 • Published 10 months ago

@jotter/from-now v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

fromNow

Very flexible relative time formatting function. You can quickly get formatted times like 2 minutes ago, 3 weeks ago, 5 years from now.

You can also generate a display that fits your needs by customizing the locale and thresholds used in the formatting.

简单灵活的相对时间格式化函数。可以快速获取像 2分钟前,3周前,5年后 的格式化时间。

您还可以通过自定义格式化中使用的语言和阈值,生成合适的显示方式。

Install

npm

npm install @jotter/from-now

browser

https://cdn.jsdelivr.net/npm/@jotter/from-now/dist/index.global.js

Usage

import fromNow from '@jotter/date-now'

fromNow('2023-06-16 12:50:20')  // now
fromNow('2023-06-16')  // 13 hours ago
fromNow('2023-06-15')  // 2 days ago
fromNow('2023-06')  // 2 weeks ago
fromNow('2023')  // 6 months ago
fromNow('2022')  // a year ago
fromNow('2028')  // in 5 years

// 更改当前环境语言
fromNow.locale('zh')

fromNow('2023-06-16 12:50:20')  // 刚刚
fromNow('2023-06-16')  // 13 小时前
fromNow('2023-06-15')  // 2 天前
fromNow('2023-06')  // 2 周前
fromNow('2023')  // 6个月前
fromNow('2022')  // 1 年前
fromNow('2028')  // 5 年后

或者创建新的实例:

import { create } from '@jotter/date-now'

const fromNow = create({
  locale: {},
  thresholds: {}
})

fromNow('2023-06-16')  // 13小时前
fromNow('2023-06-15')  // 2天前
fromNow('2023-06')  // 2周前
fromNow('2023')  // 6个月前
fromNow('2022')  // 1年前

API

1. fromNow()

相对时间格式化函数

fromNow(date)

methods

locale(name, config)

更改相对时间格式化字符串对象或语言环境。

  • name: 语言环境, 'en' | 'zh'
  • config: 格式化字符串对象

thresholds(config)

更改时间段阈值。

  • config: 时间段阈值对象

2. create()

创建一个新的相对时间格式化函数。

const fromNow = create(locale, thresholds)

fromNow(date)
  • locale : 相对时间格式化字符串对象或语言环境
    • type : 'en' | 'zh' | object
  • thresholds : 时间段阈值对象
    • type : object

时间段 (thresholds)

moment.js 一致.

范围Key示例输出
0 到 44 秒s几秒钟前
取消设置SS44 秒前
45 至 89 秒m一分钟前
90 秒到 44 分钟mm2 分钟前... 44 分钟前
45 至 89 分钟h一小时前
90 分钟到 21 小时hh2 小时前 ... 21 小时前
22 至 35 小时d一天前
36 小时至 25 天dd2 天前 ... 25 天前
26 至 45 天M一个月前
45 至 319 天MM2 个月前 ... 10 个月前
320 至 547 天(1.5 年)y一年前
548 天+yy2 年前 ... 20 年前

格式化字符串对象 (locale)

{
  future: 'in %s',
  past: '%s ago',
  s: 'a few seconds',
  ss: '%d seconds',
  m: 'a minute',
  mm: '%d minutes',
  h: 'an hour',
  hh: '%d hours',
  d: 'a day',
  dd: '%d days',
  w: 'a week',
  ww: '%d weeks',
  M: 'a month',
  MM: '%d months',
  y: 'a year',
  yy: '%d years',
}

说明: 1. 如果字符串包含%ns,则表示不显示后缀。 比如 { s: '刚刚%ns' }; 2. 如果格式对象属性值为数组,比如 { s: ['刚刚%ns', '很快%ns'] }

  • [0]表示 past 的格式化结果
  • [1]表示 future 的格式化结果