我想在js模块的lit元素中显示json数据库中每个条目(日期、文本、问题、答案(的日期。jsondb中(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)}
在点亮的元素内部被调用时,它会抛出
RangeError: Invalid time value.
根据文件的日期,formatWithOptions()
应该可以与"d MMMM, yyyy, h:mm a"
通话。这篇文章处理了相同的错误,但使用了不同的函数(formatDistanceToNow
(。我的变量哪里出了问题?
如果未定义x
,下面的代码将生成无效日期。
const newDate = (x) => new Date(x);
另外,不要忘记,您需要执行compose函数来为newDate
函数提供输入。
下面的代码应该可以工作:
const MY_DATE_STR = "2021-12-24T21:06:06.773Z";
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)(MY_DATE_STR);
console.log(prettyDate); // 24 December, 2021, 1:06 PM