我如何改进 returns 在 >= ES6 中创建时间差异的方法,例如(30s、5m、3h、1y 前)
how can i improve method that returns created time diff like ( 30s, 5m, 3h, 1y ago ) in >= ES6
这是我的代码
我想要实现的是与 youtube/fb/instagram 相似的时间,显示发布时间差异
喜欢:
30 多年前
5m 前
15 小时前
6天前
1 周前
5 年前
代码工作正常,但过于冗长,我想知道是否有一些 js "guru" 可以使用 ecmascript
的最新功能改进它
const timeAgo = () => {
const date1 = dayjs(Date.now())
const now = base.createdOn
const diffInSeconds = date1.diff(now, 'second', false)
let diff = date1.diff(now, 'second', false) + 's'
if (diffInSeconds > 60 * 60 * 24 * 7 * 30 * 12) {
return date1.diff(now, 'year', false) + 'y'
}
if (diffInSeconds > 60 * 60 * 24 * 7 * 30) {
return date1.diff(now, 'month', false) + 'm'
}
if (diffInSeconds > 60 * 60 * 24 * 7) {
return date1.diff(now, 'week', false) + 'w'
}
if (diffInSeconds > 60 * 60 * 24) {
return date1.diff(now, 'day', false) + 'd'
}
if (diffInSeconds > 60 * 60) {
return date1.diff(now, 'hour', false) + 'h'
}
if (diffInSeconds > 60) {
return date1.diff(now, 'minute', false) + 'm'
}
return diff
}
A for of
应该这样做,如果你让 day.js
比较你不会有逻辑错误:
const timeSince = (from, to = Date.now()) => {
to = dayjs(to);
const units = ['year', 'month', 'week', 'day', 'hour', 'minute'];
for (let unit of units){
const diff = to.diff(from, unit, false);
if(diff) {
return diff + unit.charaAt(0); // you are using m for month and minute...
}
}
// base case if there are no seconds difference
return to.diff(now, 'second', false) + 's';
}
// timeSince(base.createdOn)
这是我的代码
我想要实现的是与 youtube/fb/instagram 相似的时间,显示发布时间差异
喜欢: 30 多年前 5m 前 15 小时前 6天前 1 周前 5 年前
代码工作正常,但过于冗长,我想知道是否有一些 js "guru" 可以使用 ecmascript
的最新功能改进它 const timeAgo = () => {
const date1 = dayjs(Date.now())
const now = base.createdOn
const diffInSeconds = date1.diff(now, 'second', false)
let diff = date1.diff(now, 'second', false) + 's'
if (diffInSeconds > 60 * 60 * 24 * 7 * 30 * 12) {
return date1.diff(now, 'year', false) + 'y'
}
if (diffInSeconds > 60 * 60 * 24 * 7 * 30) {
return date1.diff(now, 'month', false) + 'm'
}
if (diffInSeconds > 60 * 60 * 24 * 7) {
return date1.diff(now, 'week', false) + 'w'
}
if (diffInSeconds > 60 * 60 * 24) {
return date1.diff(now, 'day', false) + 'd'
}
if (diffInSeconds > 60 * 60) {
return date1.diff(now, 'hour', false) + 'h'
}
if (diffInSeconds > 60) {
return date1.diff(now, 'minute', false) + 'm'
}
return diff
}
A for of
应该这样做,如果你让 day.js
比较你不会有逻辑错误:
const timeSince = (from, to = Date.now()) => {
to = dayjs(to);
const units = ['year', 'month', 'week', 'day', 'hour', 'minute'];
for (let unit of units){
const diff = to.diff(from, unit, false);
if(diff) {
return diff + unit.charaAt(0); // you are using m for month and minute...
}
}
// base case if there are no seconds difference
return to.diff(now, 'second', false) + 's';
}
// timeSince(base.createdOn)