使用原生Date对象比较时间:将起始、结束和目标时间转为Date实例,通过逻辑判断目标时间是否在区间内,如target > start && target < end即可判断。

在 JavaScript 中判断一个时间点是否在两个时间之间,通常可以通过 Date 对象来实现。下面介绍几种常见且实用的方法。
JavaScript 的 Date 对象支持直接比较时间戳。你可以将起始时间、结束时间和目标时间都转换为 Date 实例,然后通过逻辑判断目标时间是否在区间内。
const start = new Date('2023-10-01T08:00:00'); const end = new Date('2023-10-01T18:00:00'); const target = new Date('2023-10-01T12:00:00'); if (target > start && target这种方式适用于包含或不包含端点的场景,只需要调整比较符即可:
为了复用方便,可以封装一个通用函数:
function isBetween(target, start, end, inclusive = false) { const t = new Date(target).getTime(); const s = new Date(start).getTime(); const e = new Date(end).getTime(); if (inclusive) { return t >= s && t s && t这个函数接受字符串或 Date 对象作为参数,第三个参数决定是否包含边界。
如果你的项目引入了 moment.js,可以使用其内置的 isBetween 方法:
const start = moment('2023-10-01 08:00'); const end = moment('2023-10-01 18:00'); const target = moment('2023-10-01 12:00'); target.isBetween(start, end); // true target.isBetween(start, end, null, '[]'); // 第四个参数控制包含性注意:moment.js 已进入维护模式,推荐新项目使用 date-fns 或 dayjs。
dayjs 是 moment.js 的现代替代品,体积小,API 简洁:
const dayjs = require('dayjs'); const isBetween = require('dayjs/plugin/isBetween'); dayjs.extend(isBetween); const start = dayjs('2023-10-01T08:00:00'); const end = dayjs('2023-10-01T18:00:00'); const target = dayjs('2023-10-01T12:00:00'); target.isBetween(start, end); // true target.isBetween(start, end, null, '()'); // 控制开闭区间基本上就这些方法。根据你是否使用第三方库,可以选择最合适的实现方式。核心思路是统一时间格式,转为可比较的时间戳或 Date 对象,再做逻辑判断。
以上就是js isBetween时间点的判断的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号