javascripthtmlcssnode.js

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>


Solution

  • It depends upon the system preferences, you cannot enforce it.