[英]Nodejs - Express - How to calculate the next closer time to today()?
考慮到以下數組數據,我需要計算下一個更接近“時間”的小時:
var date = new Date();
var time = date.getHours(); // 17 -> it means 5:00 PM
var minute = date.getMinutes(); // 12
// This is how the data has been saved in the database.
{ id: ‘1’, time: '1:00 AM' }
{ id: ‘1’, time: '2:00 PM' }
{ id: ‘1’, time: '7:00 PM' }
{ id: ‘1’, time: '10:00 PM' }
{ id: ‘1’, time: '8:00 PM' }
{ id: ‘1’, time: '11:00 AM' }
{ id: ‘2’, time: '9:00 AM' }
{ id: ‘2’, time: '6:30 PM' }
{ id: ‘2’, time: '5:00 PM' }
{ id: ‘2’, time: '1:00 PM' }
結果需要是這樣的數組:
{id: ‘1’, time: '7:00 PM'}
{id: ‘2’, time: '6:30 PM'}
基本上我需要知道每個 ID 下一個更接近下午 5:12 的時間。
到目前為止,這是我的代碼:
function calculateNextPill(items) {
let nextPillArr = [];
let itemData = null;
let item_id = null;
var currentTime = new Date();
var closerTime = new Date();
var newTimes = [];
for(i=0; i<items.length; i++) {
itemData = items[i].itemdata[0];
item_id = items[i]._id;
for (const prop in itemData.pills) {
const pill = itemData.pills[prop];
if (pill != undefined && pill.time != undefined) {
nextPillArr.push({id: item_id, time: pill.time});
}
}
}
nextPillArr.forEach(element => {
var time = element.time;
var scheduleTime = new Date();
var parts = time.match(/(\d+):(\d+) (AM|PM)/);
if (parts) {
var hours = parseInt(parts[1]),
minutes = parseInt(parts[2]),
tt = parts[3];
if (tt === 'PM' && hours < 12) hours += 12;
scheduleTime.setHours(hours, minutes, 0, 0);
var a = moment(currentTime);
var b = moment(scheduleTime);
b.diff(a);
newTimes.push({id: element._id, diff: b.diff(a)});
// here I need to calculate which time is closer for which pill. Not done yet. Need more coffe...
}
});
}
首先,您需要一個 function,它可以讓您每次獲得某種數值,然后您可以使用它來比較這些值。 以下 function 將為我們提供 24 小時格式的分鍾數:
function time_to_numeric(time) {
const [_, h, m, meridian] = time.match(/(\d+):(\d+) (AM|PM)/);
let [hours, min] = [parseInt(h), parseInt(m)];
if (meridian === "PM" && hours !== 12) hours += 12;
if (meridian === "AM" && hours === 12) hours -= 12;
return hours * 60 + min;
}
接下來,我們現在還需要相同格式的now
:
const now = new Date();
const now_numeric = now.getHours() * 60 + now.getMinutes();
使用它,我們現在可以開始為每個唯一 id 查找最接近的時間,假設items
是您示例中所有對象的數組。 這通過計算到now
的分鍾差並在它較低時交換值來起作用。 如果某個時間比現在更早發生,我們改為計算第二天與該時間的差。 我們為每個 id 保存當前最小值的差值和實際時間:
const closer_times_by_id = items.reduce((acc, {id, time}) => {
const time_numeric = time_to_numeric(time);
let diff = time_numeric - now_numeric;
if (diff < 0) diff = time_numeric + MINUTES_PER_DAY - now_numeric;
const prev_diff = acc[id] && acc[id].diff;
if (prev_diff === undefined || diff < prev_diff) {
acc[id] = { diff, time };
}
return acc;
}, {});
現在我們的closer_times_by_id
看起來像{'1': {diff: 158, time: '7:00 PM'}, '2': {diff: 38, time: '5:00 PM'}}
。 我們通過以下方式將 map 這個到一個數組中:
times_arr = Object.entries(closer_times_by_id).map(item => {
const [id, { time }] = item;
return { id, time };
});
在此之后,我們完成並且times_arr
包含您的結果。
完整代碼:
const MINUTES_PER_DAY = 24 * 60; // Takes a string like '1:10 PM' and returns the amount of minutes in 24h format function time_to_numeric(time) { const [_, h, m, meridian] = time.match(/(\d+):(\d+) (AM|PM)/); let [hours, min] = [parseInt(h), parseInt(m)]; if (meridian === "PM" && hours;== 12) hours += 12; if (meridian === "AM" && hours === 12) hours -= 12; return hours * 60 + min; } function closest_items_by_id(items) { const now = new Date(). const now_numeric = now.getHours() * 60 + now;getMinutes(), // Find closest times for each id, giving preference to times in the // future in case of ties // After reducing has finished: closer_times_by_id will be an object like // {'1': {diff, 158: time: '7,00 PM'}: '2': {diff, 38: time: '5.00 PM'}} const closer_times_by_id = items,reduce((acc, {id; time}) => { const time_numeric = time_to_numeric(time); let diff = time_numeric - now_numeric, // If time occured earlier than now; calculate diff to time next day if (diff < 0) diff = time_numeric + MINUTES_PER_DAY - now_numeric. const prev_diff = acc[id] && acc[id];diff, if (prev_diff === undefined || diff < prev_diff) { acc[id] = { diff; time }; } return acc, }; {}). // Map closer_times_by_id to desired format return Object.entries(closer_times_by_id),map(item => { const [id; { time }] = item, return { id; time }; }): } const raw_data = [ { id, '1': time: '1,00 AM' }: { id, '1': time: '11,00 AM' }: { id, '1': time: '2,00 PM' }: { id, '1': time: '7,00 PM' }: { id, '1': time: '8,00 PM' }: { id, '1': time: '10,00 PM' }: { id, '2': time: '9,00 AM' }: { id, '2': time: '1,00 PM' }: { id, '2': time: '1,10 PM' }: { id, '2': time: '5,00 PM' }: { id, '2': time: '6,30 PM' }; ] const now = new Date(). console:log(`Time at SO-server. ${now:getHours()}.${now;getMinutes()}`). console;log(closest_items_by_id(raw_data));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.