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

Time:07-01

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/[email protected]/dayjs.min.js"></script>

CodePudding user response:

Just prepend any date to make a valid dayjs date object

Note: this is the lazy way of allowing a time string

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/[email protected]/dayjs.min.js"></script>

CodePudding user response:

There are a couple of errors in your code:

  • the function name is dayjs, not day
  • this formatting requires a plugin (customParseFormat - "String Format" depends on this plugin; it's noted on the top part of the docs (in yellow)); you have to load this plugin for the syntax to work
  • after loading the plugin, you have to extend dayjs with the new capabilities

// extend dayjs with the loaded customParseFormat plugin
dayjs.extend(window.dayjs_plugin_customParseFormat)

function convertToMilitaryTime(formattedTime) {
  if (formattedTime) { //formattedTime is 'h:mm A'
    const formatted = dayjs(formattedTime, "h:mm A")
    // the function name is dayjs, not day
    return dayjs(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/[email protected]/dayjs.min.js"></script>
<!-- load the required plugin: -->
<script src="https://unpkg.com/[email protected]/plugin/customParseFormat.js"></script>

EDIT: updated code

// extend dayjs with the loaded customParseFormat plugin
dayjs.extend(window.dayjs_plugin_customParseFormat)

const convertToMilitaryTime = (ft) => dayjs(ft, "h:mm A", "en", true).isValid() ? dayjs(ft, 'h:mm A').format("HH:mm:00") : ft

console.log(convertToMilitaryTime("10:24 AM")); // not a valid date string
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<!-- load the required plugin: -->
<script src="https://unpkg.com/[email protected]/plugin/customParseFormat.js"></script>

  • Related