Search code examples
javascripttypescriptdayjs

Formatting 12 hour time (h:mm A) to 24 hour time (HH:mm:00) in day.js


I am trying to make a time conversion function that takes time in as "h:mm A" and converts it to military time (HH:mm:00) in day.js, but am struggling to figure it out. I was able to complete this task without dayjs but can't quite figure it out with dayjs. Here is my attempt at it:

The 00 is there as I want the seconds to default to 00. Thank you!

function convertToMilitaryTime(formattedTime) {
  if (formattedTime) { //formattedTime is 'h:mm A'
    const formatted = dayjs(formattedTime, "h:mm A")
    return day(formattedTime, ['h:mm A']).format("HH:mm:00")
  }
  return formattedTime;
}
console.log(convertToMilitaryTime("10:24 AM")); // not a valid date string
<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>


Solution

  • Just prepend any date to make a valid dayjs date object

    Note: this is the lazy way of allowing a time string. To adhere to the documentation of dayJS. look at the other answer

    Or don't use dayJS at all

    const ampm2military = ampm => ampm ? dayjs(`1/1/1 ${ampm}`).format("HH:mm:00") : null;
    
    console.log(ampm2military("1:24 PM"));
    <script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.3/dayjs.min.js"></script>