Solve - date.format is not a function in JavaScript


Borislav Hadzhiev

Wed Oct 20 20212 min read


Photo by pparnxoxo

Solve - date.format is not a function #

The "date.format is not a function" error occurs because the format method is not implemented in JavaScript. To solve the error, use a third party package to format your dates, e.g. moment or date-fns.

typeerror dateformat is not a function

Here is an example of how the error occurs.

const date = new Date(); // โ›”๏ธ TypeError; date.format is not a function const result = date.format('MM-DD-YYYY');

We tried to call a method named format() on the Date object and got the error back.

This is because a format method is not natively implemented in JavaScript.

To solve the error, you can install a third party package like moment or date-fns.

This article shows how to use both, however my personal recommendation would be to go with date-fns as it is more modern and is not as heavy on the bundle like moment.

Like their docs say, date-fns is like lodash for dates.

First, install the package:

npm i date-fns

Now, you can use the format function in the following way.

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

Note that if your project does not have a package.json file yet, you would have to create one using the npm init -y command.

The format function takes a date as the first parameter, a string for how the date should be formatted as the second and returns the formatted date.

For more examples, check out the format section of the date-fns docs.

You can achieve the same result by using the moment package, which is also very popular.

To install the package, run the following command.

npm i moment

Now, you are able to format a date in the following way.

import moment from 'moment'; const d1 = new Date(); console.log(d1); const result = moment(d1).format('MM-DD-YYYY'); console.log(result); // ๐Ÿ‘‰๏ธ 12-16-2021

Here are some more examples of how to use the format method in moment.

However, especially for frontend projects, be aware that the moment library is about 300Kb. When gzipped, it still adds about 72.3 Kb to your bundle, which would slow your site down.

In my opinion the better, more modern alternative - date-fns should always be preferred when formatting dates.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee