3
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
ashwin1014
  • 351
  • 1
  • 5
  • 18

2 Answers2

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"

SeanMC
  • 1,960
  • 1
  • 22
  • 33
3

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>
Carlos1232
  • 815
  • 6
  • 15