Search code examples
javascripttime-formatdayjs

Dayjs: unable to format custom 24hr time to 12hr


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

when executing something like this "dayjs().format('18:00', "hh:mm A");" , it does not convert to 12 hr timing.... returns 18:00

How do i get outputs converted using dayjs like:

 08:00 -> 08:00 AM
 18:00 -> 06:00 PM

Solution

  • For doing that you can't just set the '18:00', you have to specify a date.

    var now = new dayjs().startOf('day')
    var newDate = now.add('18','hour').add('10','minutes')
    var newDatezerominutes = now.add('18','hour').add('00','minutes')
    var formatted = dayjs(newDate).format('hh:mm a')
    var formattedzero = dayjs(newDatezerominutes).format('hh:mm a')
    
    console.log(`To see differences ${formatted}`) 
    console.log(`Your case ${formattedzero}`)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.34/dayjs.min.js"></script>