我希望在js模块的lit元素中的json数据库中显示每个条目(日期、文本、问题、答案)的日期。json中(日期)的日期格式是有效的(见这篇文章)。示例:"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.根据日期-fns文档的说法,formatWithOptions()应该可以和"d MMMM, yyyy, h:mm a"联系。这个职位处理相同的错误,但使用的是不同的函数(formatDistanceToNow)。我的变量哪里出了问题?
发布于 2021-12-27 21:21:04
如果x未定义,下面的代码将生成无效日期。
const newDate = (x) => new Date(x);另外,不要忘记,您需要执行复合函数来向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 PMhttps://stackoverflow.com/questions/70500261
复制相似问题