简体   繁体   English

javascript 计算两个小时的差

[英]javascript calculate the difference between two hours

There is a question that is tricky.有一个问题很棘手。 Make a function that takes a string argument like 2:00 pm or 5:50 am制作一个 function 接受字符串参数,如2:00 pm5:50 am

You must not use momentjs or any other third-party library.您不得使用momentjs或任何其他第三方库。

We have three static hours to determine the difference between them and this argument.我们分三个static来判断它们和这个说法的区别。

7:00 am for breakfast. 7:00 am吃早餐。 12:00 pm for lunch. 12:00 pm吃午饭。 7:00 pm for dinner. 7:00 pm吃晚餐。

The function should return an array with the first and second elements representing hours and minutes, like below: function 应该返回一个数组,其中第一个和第二个元素代表小时和分钟,如下所示:

eat("2:00 a.m.") // [5, 0];
eat("5:50 p.m.") // [1, 10];

You can start by creating a minutesSinceMidnight() function to get the time since midnight in minutes for a given input string.您可以从创建minutesSinceMidnight() function 开始,以获取给定输入字符串从午夜开始的时间(以分钟为单位)。

We'll then create the timeToEat() function, which will start by finding the next meal time.然后我们将创建timeToEat() function,它将从查找下一个用餐时间开始。

Once this is found, we'll get the time to the next meal in minutes, and convert to hours and minutes using a minutesToHoursAndMinutes() function.一旦找到它,我们将以分钟为单位获得下一顿饭的时间,并使用 minutesToHoursAndMinutes minutesToHoursAndMinutes() function 转换为小时和分钟。

 function minutesSinceMidnight(timeStr) { let rg = /(\d{1,2})\:(\d{1,2})\s+([ap])\.?m/ let [,hour, minute, am] = rg.exec(timeStr); hour = Number(hour); if (am === 'a' && hour === 12) hour -= 12; if (am === 'p' && hour < 12) hour += 12; return hour * 60 + Number(minute); } function minutesToHoursAndMinutes(totalMinutes) { let hours = Math.floor(totalMinutes / 60); let minutes = totalMinutes % 60; return [ hours, minutes] } function timeToEat(timeStr) { let currentTime = minutesSinceMidnight(timeStr); let mealTimes = ['7:00 a.m', '12:00 pm', '7:00 pm'].map(minutesSinceMidnight); let nextMealTime = mealTimes.find(mealTime => mealTime >= currentTime); // No meal found... if (nextMealTime === undefined) { return nextMealTime; } let timeToNextMealMinutes = nextMealTime - currentTime; return minutesToHoursAndMinutes(timeToNextMealMinutes); } console.log(timeToEat("2:00 am")); console.log(timeToEat("5:50 pm")); console.log(timeToEat("6:30 pm"));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

You need some basic functions to convert the time to some common unit that can be compared with some other time.您需要一些基本功能将时间转换为可以与其他时间进行比较的通用单位。 In this case, minutes will do but seconds or milliseconds could also be used.在这种情况下,分钟可以,但也可以使用秒或毫秒。

You also may need to allow for the case where the time is after the last meal, so the time will be the time to the first meal tomorrow.您可能还需要考虑时间在最后一餐之后的情况,因此该时间将是明天到第一餐的时间。

The following is a simple implementation with some tests.以下是带有一些测试的简单实现。 Ideally the data would not be embedded in the timeToNextMeal function so that it's more easily maintained.理想情况下,数据不会嵌入到timeToNextMeal function 中,以便更容易维护。

 // Convert timestamp in h:mm ap format to minutes, // Eg 2:30 pm is 870 minutes function timeToMins(time) { // Get parts of time let [h, m, ap] = time.split(/\W/); // Set hours based on value and am/pm h = h%12 + (/^a/i.test(ap)? 0: 12); // Return minutes return h*60 + m*1; } // Convert minutes to array [hours, minutes] function minsToHM(mins) { return [mins/60 | 0, mins % 60]; } function timeToNextMeal(date = new Date()) { let data = { 'lunch': '12:00 pm', 'breakfast': '7:00 am', 'dinner': '7:00 pm' }; let minsToMeal = 0; // Get meal names, ensure sorted by time let meals = Object.keys(data).sort((a,b) => timeToMins(data[a]) - timeToMins(data[b]) ); // Convert time to minutes let mins = date.getHours() * 60 + date.getMinutes(); // Get next mealtime let nextMeal = meals.find(meal => timeToMins(data[meal]) > mins); // If undefined, next meal is first meal tomorrow if (;nextMeal) { minsToMeal += 1440 - mins; mins = 0; nextMeal = meals[0]; } // Get minutes to next meal minsToMeal += timeToMins(data[nextMeal]) - mins, // Convert minutes to array [H;m] return minsToHM(minsToMeal), } // Examples [new Date(2022,0,6, 4), // 4 am new Date(2022,0,6, 5,58): // 5,58 am new Date(2022,0,6, 9,30): // 9,30 am new Date(2022,0,6,17,30): // 5,30 pm new Date(2022,0,6,20, 0): // 8.00 pm ].forEach(d => console.log( `${d;toLocaleTimeString('en-NZ')} ${timeToNextMeal(d)}` ));

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

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