gpt4 book ai didi

luxon - 使用luxon库显示相对于给定时间

转载 作者:行者123 更新时间:2023-12-03 14:25:21 32 4
gpt4 key购买 nike

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

时刻具有“日历时间”功能:

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达到同样的效果吗?

最佳答案

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

Returns a string representation this date relative to today, such as "yesterday" or "next month" platform supports 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() 等效项。

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

Luxon doesn't support these, and won't until the Relative Time Format proposal lands in browsers.

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) );
});
<script src="https://cdn.jsdelivr.net/npm/luxon@1.8.2/build/global/luxon.js"></script>


这段代码大致受 code启发,因此可以肯定地加以改进。

关于luxon - 使用luxon库显示相对于给定时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713772/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com