[英]Correct Date format in formatWithOptions results in Range Error: Invalid time value
我想在 js 模块中的 lit 元素中显示 json 数据库中每个条目(日期、文本、问题、答案)的日期。 json db 中 (date) 的日期格式是有效的( 参见这篇文章)。 示例: "2021-12-24T21:06:06.773Z"
相关代码:
import { formatWithOptions } from "date-fns/fp";
import compose from "crocks/helpers/compose";
...
const newDate = (x) => new Date(x);
const formatDateWithOptions = formatWithOptions(
{
awareOfUnicodeTokens: true,
},
"d MMMM, yyyy, h:mm a"
);
const prettyDate = compose(formatDateWithOptions, newDate); // this is registering as an invalid date
当${prettyDate(date)}
在 lit 元素中被调用时,它会抛出
RangeError: Invalid time value.
根据date-fns docs , formatWithOptions()
应该可以用"d MMMM, yyyy, h:mm a"
调用。 这篇文章处理相同的错误,但使用了不同的 function ( formatDistanceToNow
)。 我的变量哪里出错了?
如果x
未定义,下面的代码将生成无效日期。
const newDate = (x) => new Date(x);
另外,不要忘记您需要执行 compose function 来为newDate
function 提供输入。
下面的代码应该可以工作:
const newDate = x => {
if (x === undefined) { return new Date(); }
return new Date(x);
}
const formatDateWithOptions = formatWithOptions(
{
awareOfUnicodeTokens: true,
},
"d MMMM, yyyy, h:mm a"
);
const prettyDate = compose(formatDateWithOptions, newDate)();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.