1

I want to format 12-hour time to 24-hour time using format() function from date-fns library, however, I got an error.

This is the code:

 import {format} from 'date-fns'

 const convertFrom12HourTimeTo24HourTime = (twelveHourTime: TwelveHourTime) => {
    const { hour, minute, meridiem } = twelveHourTime;

    const toFormatTime = new Date(`${hour}:${minute} ${meridiem}`);

    const formattedTime = format(toFormatTime, 'HH:mm');

    console.log(formattedTime);
}
Esa Kurniawan
  • 527
  • 1
  • 2
  • 15

1 Answers1

0

This should work if you want to use parse from date-fns:

import { parse, format } from 'date-dns'

const convertFrom12HourTimeTo24HourTime = ({ hour, minute, meridiem }: TwelveHourTime) => {
    const toFormatTime = parse(`${hour} ${minute} ${meridiem}`, 'h m a', new Date())

    const formattedTime = format(toFormatTime, 'HH:mm');

    console.log(formattedTime);
}
some-user
  • 3,888
  • 5
  • 19
  • 43