How to enforce 24Hr Format in vanilla JS

I am currently facing an issue in JS where I need to enforce a 24-hour format in each time input but, in MAC only it is showing a 12-hour format. I could not find useful solutions, most of them suggested using a date-picker package but that I don’t want to do.
Is there any possible solution to this problem?

Here is the screenshot
enter image description here

Here is my code

const dateTimeString = (timestamp) => {
  return new Date(timestamp).toISOString().substring(0, 16);
};

function createElement({
  type,
  attributes = {},
  innerText
}) {
  const element = document.createElement(type);
  Object.keys(attributes).forEach((item) => {
    element.setAttribute(item, attributes[item]);
  });
  element.textContent = innerText;
  return element;
}

const extensionForContainer = document.getElementById("extension-container")
const extensionInput = createElement({
  type: 'input',
  attributes: {
    class: 'date-input hidden',
    type: 'datetime-local',
    name: 'newEndsOn',
    id: 'newEndsOn',
    value: dateTimeString(1698196920),
  },
});
extensionForContainer.appendChild(extensionInput);
<html>
  <div id="extension-container">
  </div>
</html>

  • 1

    what do you mean ‘in MAC only’? Looks to be browser specific, and based on the user’s OS, from the docs: ‘the displayed date and time are formatted according to the user’s locale as reported by their operating system’

    – 




  • 1

    Also relevant discussion on an old Firefox bug

    – 

Leave a Comment