Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

196
Visualizações
How to get a Date object from a 12 hour time string

I am trying to provide a default value for a TimePicker object. But the that value I have is a string e.g "12:00 PM" And the picker needs a Date object.

I tried parsing the time directly into a Date object like shown below, but it does not work

let startTime = new Date("12:00 PM");

How can i convert this time string into a Date object so that i can provide the default value to the TimePicker.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

HTML:

<input id="appt-time" type="time" name="appt-time" value="13:30">

JS

const timeFrom12hto24h = time12h => {
  const [time, meridiem] = time12h.split(" ");
  let [hours, minutes] = time.split(":");
  if (hours === "12") hours = "00";
  if (meridiem === "PM") hours = parseInt(hours, 10) + 12;
  return {hours, minutes}
};

const getMyObjectTime= timeFrom12hto24h('12:00 PM');

// apply the time to the HTML element
document.getElementById("appt-time").value = getMyObjectTime.hours + ':' + getMyObjectTime.minutes;

// one way to generate the needed time object
const dateInMiliseconds = new Date().setHours(getMyObjectTime.hours, getMyObjectTime.minutes, 0)
console.log(dateInMiliseconds);

In case there is moment.js already used in the project it would be like this:

HTML:

<input id="appt-time" type="time" name="appt-time" value="13:30">

JS:

// apply the time to the HTML element
document.getElementById("appt-time").value = moment("01:00 PM", 'hh:mm A').format('HH:mm')

// one way to generate the needed time object
let [hour, minutes] =  moment("01:00 PM", 'hh:mm A').format('HH,mm').split(',');
const dateInMiliseconds = new Date().setHours(hour,minutes, 0)
console.log(dateInMiliseconds);
about 4 years ago · Santiago Trujillo Relatório

0

Ive been able to create a function that can do the conversion, since I did not find any solution to this.

const dateFromTime = ({ timeString }) => {
    const dateTime = new Date();
    let timeHours = parseInt(timeString.substring(0, 2));
    let timeMinutes = parseInt(timeString.substring(3, 5));
    let timeAMPM = timeString.substring(6,
    if (timeAMPM === "PM") {
        timeHours += 12;

    dateTime.setHours( timeHours, timeMinutes, 0, 0);
    return dateTime;
}
const dateTime = dateFromTime({ timeString: "12:00 PM" });

This get the current date and time and instead sets the time to the specified time. and returns that

For any improvements, please suggest the right way to do this.

about 4 years ago · Santiago Trujillo Relatório

0

You just need to give the correct format to the Date object.

solution 1

If you don't care about date then you can simply convert like this.

let startTime = new Date(`2022/01/01 12:00 PM`);

solution 2

If you need today's date then you can simply convert like this.

let startTime = new Date(`${new Date().toDateString()} 12:00 PM`)
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda