迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中 TypeError: date.format is not a function 错误

作者:迹忆客 最近更新:2023/01/20 浏览次数:

出现“date.format is not a function”错误是因为格式方法未在 JavaScript 中实现。

要解决该错误,需要使用第三方包来格式化我们的日期,例如 momentdate-fns

下面是产生上述错误的示例

const date = new Date();

// ⛔️ TypeError; date.format is not a function
const result = date.format('MM-DD-YYYY');

JavaScript 中 TypeError- date.format is not a function 错误

我们试图在 Date 对象上调用一个名为 format() 的方法并返回错误。

这是因为格式方法不是在 JavaScript 中本地实现的。

要解决该错误,您可以安装第三方软件包,例如:

  • moment
  • date-fns

本文展示了如何同时使用这两者,但是,我的建议是使用 date-fns,因为它更现代并且不像 moment.js 那样在捆绑包中那么繁重。

与文档状态一样,date-fns 就像日期的 lodash。

首先,通过在项目的根目录(package.json 文件所在的位置)中打开终端并运行以下命令来安装包。

# 👇️ 如果你必须创建一个 package.json 文件
$ npm init -y

# 👇️ 安装 NPM
$ npm install date-fns

# 👇️ 或者安装使用 YARN
$ yarn add date-fns

现在,我们可以按以下方式使用格式功能。

import {format} from 'date-fns';

const d1 = new Date('Sept 24, 22 13:20:18');

const result = format(d1, 'yyyy-MM-dd');
console.log(result); // 👉️ 2022-09-24

如果我们的项目还没有 package.json 文件,请使用 npm init -y 命令创建一个。

format 函数将日期作为第一个参数,一个表示日期应如何格式化为第二个参数的字符串,并返回格式化后的日期。

有关更多示例,请查看 date-fns 文档的格式部分。

使用 moment.js 格式化日期

我们可以使用同样非常流行的 moment 包来获得相同的结果。

要安装软件包,请运行以下命令。

# 👇️ 安装使用 NPM
$ npm install moment

# 👇️ 安装使用 YARN
$ yarn add moment

现在,我们可以按以下方式格式化日期。

import moment from 'moment';

const d1 = new Date();
console.log(d1); // 👉️ 2022-12-31T10:07:42.805Z

const result = moment(d1).format('MM-DD-YYYY');
console.log(result); // 👉️ 12-31-2022

下面是更多关于如何使用格式化方法的示例。

但是,特别是对于前端项目,请注意 moment 库大约有 300Kb。 压缩后,它仍然会向您的包中添加大约 72.3 Kb,这会减慢您的网站速度。

在我看来,在格式化日期时,应该始终首选更轻便、更现代的 date-fns 包。


总结

出现“date.format is not a function”错误是因为格式方法未在 JavaScript 中实现。

要解决该错误,请使用第三方包来格式化您的日期,例如 momentdate-fns

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便