从 Moment 迁移到 Luxon - (t) => moment(t).format('hh:mm') 等效
我正在将一段旧代码从 Moment 迁移到 Luxon,并遇到下面的函数:
export const TIME_FORMATTER = {
HOUR: (t) => moment(t).format('hh:mm'),
DAY: (t) => moment(t).format('M/DD'),
HOUR_PERIOD: (t) => moment(t).format('hh:mm A'),
DAY_HOUR_PERIOD: (t) => moment(t).format('hh:mm A M/DD'),
SEC: (t) => moment(t).format('HH:mm:ss')
};
其调用方式如下:
export const getFormatterByTimeInterval = (timeInterval: number) => {
if (timeInterval <= 240) {
return TIME_FORMATTER.DAY_HOUR_PERIOD;
}
else if (timeInterval > 480) {
return TIME_FORMATTER.HOUR_PERIOD;
}
else {
return TIME_FORMATTER.DAY;
}
}
我最初的想法是与 Luxon 使用相同的调用格式:
const TIME_FORMATTER_LUXON = {
HOUR: (t) => DateTime.local(t).toFormat("hh:mm"),
DAY: (t) => DateTime.local(t).toFormat("M/d"),
HOUR_PERIOD: (t) => DateTime.local(t).toFormat("t"),
DAY_HOUR_PERIOD: (t) => DateTime.local(t).toFormat("t M/d"),
SEC: (t) => DateTime.local(t).toFormat("HH:mm:ss")
};
这在另一个文件 const formatter 上调用= getFormatterByTimeInterval(timeInterval);
但它返回 Invalid DateTime
这对于 Luxon 来说可能吗?可能是什么问题?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,您的旧代码可能有一些问题,所以我想至少在回答您的问题之前解决这些问题:
接受
number
moment 的唯一函数签名code> 参数是 Unix 时间戳(毫秒):我不确定格式化程序解析器函数中的
timeInterval
参数代表什么:但我现在会忽略它。排除这一点,让我们看看条件:
我不确定你的程序应该如何工作,但这对我来说似乎不是预期的行为。
关于您的转换问题:
从毫秒
number
类型实例化DateTime
的Luxon
等效项是DateTime.fromMillis()
。 (您无需担心使用local
方法,因为 luxon 默认情况下使用系统的本地时区。)关于等效的格式选项,它们将是:
hh:mm
hh:mm
M/DD
L/dd
hh:mm A
hh:mm a
hh:mm AM/DD
hh:mm a L/dd
>时:分:秒
HH:mm:ss
表示为代码,它看起来像这样:
然后,对解析器进行一个小的重构:
您可以像这样检查它:
TypeScript Playground 中的代码
来自 TS Playground 的已编译 JavaScript 演示链接:
It seems to me like your old code might have a few issues, so I want to at least address them before responding to your question:
The only function signature for
moment
which accepts anumber
argument is Unix Timestamp (milliseconds):I'm not sure what the
timeInterval
parameter represents in your formatter resolver function:but I'll ignore that for now. With that out of the way, let's look at the conditionals:
I'm not sure how your program is supposed to work, but that doesn't seem like the intended behavior to me.
In regard to your question of conversion:
The
Luxon
equivalent for instantiation of aDateTime
from a millisecondsnumber
type isDateTime.fromMillis()
. (You don't need to worry about using thelocal
method because luxon uses your system's local timezone by default.)In regard to the equivalent formatting options, they would be:
hh:mm
hh:mm
M/DD
L/dd
hh:mm A
hh:mm a
hh:mm A M/DD
hh:mm a L/dd
HH:mm:ss
HH:mm:ss
Expressed as code, it looks like this:
Then, a small refactor of your resolver:
And you can check it like this:
Code in the TypeScript Playground
Demo of compiled JavaScript from the TS playground link: