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.
CodePudding user response:
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>