admin管理员组

文章数量:1327483

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
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
Share Improve this question asked Aug 26, 2020 at 17:29 ashwin1014ashwin1014 3711 gold badge5 silver badges18 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

I took the accepted answer and simplified it a bit for my use case. Which is pretty much the same use case.

If the date doesn't matter, and you are only trying to convert time -then this should be all you need.

const globalTime = "14:00";
const twelveHourTime = dayjs('1/1/1 ' + globalTime).format('hh:mm a')
// twelveHourTime = "02:00 pm"

Since you need a full date for dayjs to format it, but the only output is the time, then the date is irrelevant and can just be anything. Like, "1/1/1"

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./ajax/libs/dayjs/1.8.34/dayjs.min.js"></script>

本文标签: javascriptDayjs unable to format custom 24hr time to 12hrStack Overflow