最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - dayjs return invalid date from format string - Stack Overflow

programmeradmin10浏览0评论

I try to parse the date from a string but I got invalid date.

Seems I doing something incorrect here but can't find out why. I give the string and the format to parse from. as I say I get invalid date.

How to do it correctly?

import dayjs from 'dayjs';

console.clear();

const i = '28-04-2021';

const b = dayjs(i, 'DD-MM-YYYY').toDate();

console.log({ b }); // output invalid date.

codesandbox.io

I try to parse the date from a string but I got invalid date.

Seems I doing something incorrect here but can't find out why. I give the string and the format to parse from. as I say I get invalid date.

How to do it correctly?

import dayjs from 'dayjs';

console.clear();

const i = '28-04-2021';

const b = dayjs(i, 'DD-MM-YYYY').toDate();

console.log({ b }); // output invalid date.

codesandbox.io

Share Improve this question asked May 8, 2021 at 8:47 Jon SudJon Sud 11.7k31 gold badges104 silver badges228 bronze badges 3
  • 2 How much research effort is expected of Stack Overflow users? – Andreas Commented May 8, 2021 at 8:59
  • well, I know I can use dayjs plugin. but even without the plugin I have a constructor that takes many overload. and in the one of the options I have ctor(string, format). so I ask because seems the dayjs have built in without the plugin. this is very confuse me. – Jon Sud Commented May 9, 2021 at 4:47
  • Docs -> Parse -> String + Format: "This dependent on CustomParseFormat plugin to work" - right at the top, in a highlighted yellow box... – Andreas Commented May 9, 2021 at 9:33
Add a ment  | 

1 Answer 1

Reset to default 7

According to doc you are missing this lines of code

import customParseFormat from 'dayjs/plugin/customParseFormat';
dayjs.extend(customParseFormat);

then you can use this type of constructor dayjs(date, format).

to use it globally, i would remend to put it at the top of the project. In your example, put it right after import of dayjs.

发布评论

评论列表(0)

  1. 暂无评论