如果当前时间介于两次之间 [英] If current time is between two times using moment

查看:87
本文介绍了如果当前时间介于两次之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用momentjs查找当前本地时间是否介于两次之间。

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

我有以下代码:

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');

现在让我们假设时间 16:10 ,它应该警告TRUE,但它警告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?

推荐答案

请勿格式化从时刻返回的日期如果你打算比较它们。

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

format()返回一个字符串,而不是一个与日期/时间相当的对象。

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>

这篇关于如果当前时间介于两次之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆