【问题标题】:Correct Date format in formatWithOptions results in Range Error: Invalid time valueformatWithOptions 中的正确日期格式导致范围错误:时间值无效
【发布时间】:2021-12-27 20:45:01
【问题描述】:

我想在 js 模块中的 lit 元素内的 json 数据库中显示每个条目(日期、文本、问题、答案)的日期。 json db 中 (date) 的日期格式有效 (see this post)。示例:"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.

根据the date-fns docsformatWithOptions() 应该可以与"d MMMM, yyyy, h:mm a" 通话。 This post 处理相同的错误,但使用了不同的函数 (formatDistanceToNow)。我的变量哪里出了问题?

【问题讨论】:

    标签: javascript date-fns crocks


    【解决方案1】:

    如果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
    

    【讨论】:

      猜你喜欢
      • 2017-08-26
      • 2014-06-28
      • 1970-01-01
      • 2020-01-19
      • 2017-07-18
      • 2017-11-08
      • 1970-01-01
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多