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

170
Visualizações
Convert time string to moment.js to use .isBetween

I have a string '10:30 AM', how do I convert it to a string so I can use the .isBetween() function?

Whenever I try doing new Date(time) or moment(new Date(time)), I get "invalid date". Additionally, it says its an invalid DATE, do I have to have a date AND a time to make it valid? I assumed .isBetween could just take a time.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

ECMAScript Dates are just an offset in milliseconds since 1 Jan 1970 UTC, so are inherently date and time (UTC).

If you're using moment.js, use it to parse the string too. In this case, you have to supply the format of the string using the same tokens as for formatting (e.g. h:mm A). It's a good idea to always pass the format, otherwise it may fall back to the built–in parser, which defeats the purpose of using a library for parsing.

When given only a time, moment.js uses the current date for the year, month and day:

let s = '10:30 AM';
// <current date as YYYY-MM-DD> 10:30
console.log(moment(s, 'h:mm A').format('YYYY-MM-DD H:mm')) 

let time1 = '6:23 AM';
let time2 = '9:18 PM';
let time3 = '10:35 PM';
let format = 'h:mm A';

console.log(
  moment(time2, format).isBetween(moment(time1, format), moment(time3, format))
);

console.log(
  moment(time1, format).isBetween(moment(time2, format), moment(time3, format))
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

about 4 years ago · Juan Pablo Isaza 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