简体   繁体   English

使用Moment.js从数组获取当前的工作班次

[英]Get current working shift from array with Moment.js

Original question 原始问题

Get nearest time in the past with Moment.js 使用Moment.js获取过去的最近时间

Unfortunately the original question wasn't good enough for my use case. 不幸的是,最初的问题对于我的用例而言还不够好。 However, M. Mennan Kara's answer is answering exactly to my original question. 但是,门南·卡拉(M. Mennan Kara)的回答恰恰是对我最初的问题的回答。 So you should find it out. 因此,您应该找出答案。

Improved question with the case example can be found below. 案例示例的改进问题可以在下面找到。

Time is now 04:00 (using 24-hour clock). 现在的时间是04:00(使用24小时制)。 I'd like to parse string 22:00:00 to Moment.js object. 我想解析字符串22:00:00到Moment.js对象。

 let parsed = moment('22:00:00', 'HH:mm:ss'); 

That worked like a charm. 那就像一个魅力。 Unlikely the function returns current day by default. 默认情况下,该函数不太可能返回当前日期。 So, my question is: isn't it possible to parse to the nearest time in the past? 所以,我的问题是: 是否可以解析到最近的时间?


Improved question 改进的问题

Get current working shift from array with Moment.js 使用Moment.js从数组获取当前的工作班次

Following is an example case about how it should work in my project. 以下是有关其在我的项目中如何工作的示例。 I have working shifts in array and want to save current shift in currentShift variable. 我在数组中有工作班次,想将当前班次保存在currentShift变量中。

 let currentShift = null; let shifts = [ { name: 'early', start: '06:00:00', end: '14:00:00' }, { name: 'late', start: '14:00:00', end: '22:00:00' }, { name: 'night', start: '22:00:00', end: '06:00:00' } ]; shifts.forEach(item => { let start = moment(item.start, 'HH:mm:ss'); if (moment(item.start, 'HH:mm:ss') <= moment()) { currentShift = item; } }); 

How about if you compare the parsed time with current time and remove one day if it's after current time since you are looking for the nearest time in the past. 如果将解析后的时间与当前时间进行比较,如果在当前时间之后再删除一天,那该怎么办,因为您正在寻找过去的最近时间。

let parsed = moment('22:00:00', 'HH:mm:ss');
if (parsed.isAfter(moment())) {
    parsed.subtract(1, 'days');
}

https://jsfiddle.net/y40gvsmo/7/ https://jsfiddle.net/y40gvsmo/7/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM