How can I format time to a dayjs object?
Asked Answered
C

3

18

I have the following code


import dayjs from 'dayjs'

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

abc in console is

an invalid date

how can I make this into a valid date, the condition being the input is always going to be in format "09:00:00"

Cozen answered 15/1, 2021 at 22:23 Comment(0)
E
32

To get this to work, you'll need to enable the CustomParseFormat plugin. Then you can specify a format string for dayjs to use. For example:

const abc = dayjs("09:00:00", "HH:mm:ss");
console.log(abc);

Will result in the following:

The result of abc

You can read about the different options for the format string at the dayjs documentation: https://day.js.org/docs/en/parse/string-format

Emaemaciate answered 15/1, 2021 at 22:26 Comment(0)
C
17

If you installed dayjs using npm, you can use CustomParseFormat plugin like this.

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);
Christabelle answered 16/5, 2022 at 2:24 Comment(0)
I
0

For Angular 16+

import * as dayjs from 'dayjs';

const dayjsObjectTime = dayjs('09:00:00', 'HH:mm:ss');

Also dayjs has a method .toDate() if you want to get a Date format object from a dayjs object.

const dateObject = dayjs('09:00:00', 'HH:mm:ss').toDate()

Incandesce answered 28/2, 2024 at 7:59 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.