如何将时间格式化为 dayjs 对象?

Vik*_*hat 15 javascript reactjs dayjs

我有以下代码


import dayjs from 'dayjs'

const abc = dayjs("09:00:00")
console.log(abc)

Run Code Online (Sandbox Code Playgroud)

控制台中的 abc 是

无效日期

我怎样才能使它成为一个有效的日期,条件是输入始终采用“09:00:00”格式

tha*_*box 29

要使其正常工作,您需要启用CustomParseFormat插件。然后你可以指定一个格式字符串供dayjs使用。例如:

const abc = dayjs("09:00:00", "HH:mm:ss");
console.log(abc);
Run Code Online (Sandbox Code Playgroud)

将导致以下结果:

abc 的结果

您可以在 dayjs 文档中阅读有关格式字符串的不同选项:https://day.js.org/docs/en/parse/string-format


Cas*_*tor 16

如果您使用 npm 安装了 dayjs,则可以像这样使用 CustomParseFormat 插件。

import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";

dayjs.extend(customParseFormat);
const day = dayjs("09:00:00", "HH:mm:ss");
console.log(day);
Run Code Online (Sandbox Code Playgroud)