Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

179
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!