在 date-fns 格式 DistanceToNow 中将粒度减少到天、月、年
Reduce granularity to days, months, years in date-fns formatDistanceToNow
我使用 date-fns 库来及时计算与事件的距离。
例如:
formatDistanceToNow(nextEventDate, { addSuffix: true });
这将产生很好的人性化输出:'in about 1 month'。一切都很好,但是当距离小于一天时,相同的方法将产生如下消息:'in 1 minute' 或 'in 3 seconds' 或 'in 2 hours'.
如何减小粒度,以便如果时间范围少于一天,则结果将为 'today'?我想将输出四舍五入为年、月、周、天,但我不想要秒、分钟、小时。
我尝试了库中的不同方法(formatDistance、formatDistanceStrict)并尝试从日期参数中删除小时、分钟和秒,但是没有成功。
谢谢。
最简单的方法是手动检查小于 24 小时的距离:
import {formatDistanceToNow} from "date-fns"
function formatDistanceDay(date: Date): string {
const oneDay = 1000 * 3600 * 24;
const distance = Date.now() - date.getTime();
if (distance < oneDay && distance > 0) {
return "today";
}
return formatDistanceToNow(date, {addSuffix: true})
}
我使用 date-fns 库来及时计算与事件的距离。 例如:
formatDistanceToNow(nextEventDate, { addSuffix: true });
这将产生很好的人性化输出:'in about 1 month'。一切都很好,但是当距离小于一天时,相同的方法将产生如下消息:'in 1 minute' 或 'in 3 seconds' 或 'in 2 hours'.
如何减小粒度,以便如果时间范围少于一天,则结果将为 'today'?我想将输出四舍五入为年、月、周、天,但我不想要秒、分钟、小时。
我尝试了库中的不同方法(formatDistance、formatDistanceStrict)并尝试从日期参数中删除小时、分钟和秒,但是没有成功。
谢谢。
最简单的方法是手动检查小于 24 小时的距离:
import {formatDistanceToNow} from "date-fns"
function formatDistanceDay(date: Date): string {
const oneDay = 1000 * 3600 * 24;
const distance = Date.now() - date.getTime();
if (distance < oneDay && distance > 0) {
return "today";
}
return formatDistanceToNow(date, {addSuffix: true})
}