简体   繁体   中英

How to format only time in date fns

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);
}

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} ${minutes} ${meridiem}`, 'h m a', new Date())

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

    console.log(formattedTime);
}

Actually this question answer. You can refer this link, [convert to 24 hrs] ( convert 12-hour hh:mm AM/PM to 24-hour hh:mm )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM