If current time is between two times using moment

2020-04-19 06:38发布

问题:

I'm trying to find if the current local time is between two other times using momentjs.

I have the following code:

var currentTime = moment().format('YYYY-MM-DD HH:mm');

var prefix = 'YYYY-MM-DD ';
// the prefix is because moment expects a date prefix when parsing
var start_time = moment(prefix + '16:00').format('HH:mm');
var end_time = moment(prefix + '16:30').format('HH:mm');

if( moment(currentTime).isBetween(start_time,end_time) )
    alert('TRUE');
else
    alert('FALSE');

And now let's assume the time is currently 16:10, it should be alerting TRUE but it alerts FALSE.

Any ideas why this isn't working as intended. Is the formatting wrong?

回答1:

Don't format the dates you get back from moment if you're planning on comparing them.

format() returns a string, not a date/time-comparable object.

var currentTime = moment();

var extra = moment().format('YYYY-MM-DD') + ' ';
var start_time = moment(extra + '16:00');
var end_time = moment(extra + '16:30');

if (moment(currentTime).isBetween(start_time, end_time))
  console.log('TRUE');
else
  console.log('FALSE');
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>



回答2:

You don't need to format the date:

var currentTime = moment();

var prefix = moment();
// the prefix is because moment expects a date prefix when parsing
var start_time = prefix.add(16, 'hours');
var end_time = mprefix.add(16, 'hours').add(30, 'minutes');

if( moment(currentTime).isBetween(start_time,end_time) )
    alert('TRUE');
else
    alert('FALSE');