简体   繁体   English

排序并查找与当前时间最接近的时间

[英]Sort and find closest time from current time

I have an array of times 我有很多次

    ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM", 
     "03:00 AM", "07:00 AM", "06:00 PM"]

I want to sort them and find the nearest time from the current time, For example, Assume the time is now 05:00 PM, the above array should return the 06:00 PM as response. 我想对它们进行排序并找到与当前时间最接近的时间,例如,假设时间现在是05:00 PM,则上面的数组应返回06:00 PM作为响应。

i can able to sort them with below code 我可以用下面的代码对它们进行排序

    let sortedArray = arrayOfData.sort(function (a, b) {
    return parseInt(a.substring(0, 2)) - 
    parseInt(b.substring(0, 2));
    }) 

Can some one suggest a way to sort it properly and also to find the closest time from using the current time? 有人可以建议一种对它进行正确排序并从当前时间中找到最接近时间的方法吗? Thanks in advance 提前致谢

Just add the difference between current hour and array hours in a separate array and sort it ascending and get the first element from array this will be the most appropriate hour. 只需在一个单独的array添加当前小时与数组小时之间的差,然后对其进行升序sort ,并从array获取第一个元素,这将是最合适的小时。

Check the following snippet: 检查以下代码段:

times = ["10:00 PM","7:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM", 
     "03:00 AM", "07:00 AM", "06:00 PM"];

const currentTime = new Date();
const timeDiff = [];

times.sort((a, b) => {
  return a.indexOf('PM');
})

times.filter(time => {
  const _meridianPosition = time.indexOf('AM') > -1 ? 'AM' : 'PM';

  let _time = parseInt(time);

    if(_meridianPosition === 'PM' && _time !== 12) {
      _time += 12;
    } else if(_meridianPosition === 'AM' && _time === 12) {
      _time = 0;
    }

    const k = Math.abs(currentTime.getHours() - _time);
     timeDiff.push({hour: time, diff: k});
});

timeDiff.sort((a,b) => {
  return a.diff - b.diff;
});

console.log(timeDiff[0].hour);

Working fiddle: https://jsbin.com/zojawagiyi/6/edit?js,console 工作提琴: https ://jsbin.com/zojawagiyi/6/edit ? js,控制台

You can use the solution below, that sort the array and after this find the nearest date from the current time. 您可以使用下面的解决方案,对数组进行排序,然后从当前时间查找最近的日期。

First, the code adds the current time together with the array, and after this it gets the nearest date. 首先,代码将当前时间与数组相加,然后获得最近的日期。

 let dates = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM", "03:00 AM", "07:00 AM", "06:00 PM"]; let currentDate = new Date(); let currentTime = currentDate.getHours() + ':' + currentDate.getMinutes() + (currentDate.getHours() > 12 ? ' PM' : ' AM'); dates.push(currentTime); dates = dates.sort(function(d1, d2) { return compareDates(d1, d2); }); console.log(dates); console.log(nearestDate(dates, currentTime)); function nearestDate(dates, current) { let currentIndex = dates.indexOf(current); if(currentIndex == 0) { return dates[currentIndex + 1]; } else if (currentIndex == dates.length - 1) { return dates[currentIndex - 1]; } let previousDate = dates[currentIndex - 1]; let nextDate = dates[currentIndex + 1]; let previousDiff = diffDates(previousDate, currentTime); let nextDiff = diffDates(nextDate, currentTime); if(previousDiff < nextDiff) { return previousDate; } else { return nextDate; } } function diffDates(d1, d2) { let diffHour = Math.abs(getHour(d2) - getHour(d1)); let diffMin = Math.abs(getMin(d2) - getMin(d1)); return diffHour + diffMin; } function compareDates(d1, d2) { let t1 = getHour(d1) + ':' + getMin(d1); let t2 = getHour(d2) + ':' + getMin(d2); if (getHour(d1) == getHour(d2) && getMin(d1) < getMin(d2)) { return -1; } else if(getHour(d1) == getHour(d2) && getMin(d1) > getMin(d2)) { return 1; } if (getHour(d1) < getHour(d2)) { return -1; } if (getHour(d1) > getHour(d2)) { return 1; } return 0; } function getHour(d) { let hour = parseInt(d.split(' ')[0].split(':')[0], 10); if (d.split(' ')[1] === 'PM' && !(hour == 12)) { hour += 12; } return hour; } function getMin(d) { return parseInt(d.split(' ')[0].split(':')[1], 10); } 

I think this code will do the work. 我认为这段代码可以完成工作。 You can try this. 你可以试试看

 let currentTime = new Date(); let currentHour = parseInt(currentTime.getHours()); let availableDates = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM", "03:00 AM", "07:00 AM", "06:00 PM"]; let convertedHours = availableDates.map((date) => { let time = parseInt(date.split(' ')[0]); let period = date.split(' ')[1]; if(time === 12 && period === 'PM' ) return time; if(time < 12 && period === 'AM') return time; return time + 12; }); let getNearestTime = (convertedHours, currentHour) => { let nearestTime; let minValue = convertedHours[0] > currentHour ? (convertedHours[0] - currentHour) : (currentHour - convertedHours[0]); convertedHours.reduce((minVal, hour) => { let hourDiff = (currentHour > hour) ? currentHour - hour : hour - currentHour; if(hourDiff <= minVal) { nearestTime = hour; return hourDiff; } else { return minVal; } }, minValue) return availableDates[convertedHours.indexOf(nearestTime)]; }; console.log(getNearestTime(convertedHours, currentHour)); 

Here is the jsbin link https://jsbin.com/piwuziqeje/edit?js,console 这是jsbin链接https://jsbin.com/piwuziqeje/edit?js ,控制台

I tried a different/more intuitive approach than the ones I see here. 我尝试了一种与此处看到的方法不同/更直观的方法。 It might be a little longer than some, but it's more clear in what it's doing in my opinion. 它可能会比一些更长,但是我认为它的作用更加清楚。 The code works as you can check in the fiddle. 您可以在小提琴中检查代码的工作方式。 Here is the code: 这是代码:

var times = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM", 
 "03:00 AM", "07:00 AM", "06:00 PM"];

//Sort the array
times.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new Date('1970/01/01 ' + b);
});

//Test Sorted Array
console.log(times);

var testTime = "05:00 PM";

function findNearestTime(times, currentTime) {

//Copy given array to new array
var allTimes = times.slice();

//Push current time to new arrray
allTimes.push(currentTime);

//Sort New array
allTimes.sort(function (a, b) {
return new Date('1970/01/01 ' + a) - new    Date('1970/01/01 ' + b);
});

//Nearest time will be either the item to the left or to the right of currentTime since array is sorted
//Now we just find which one is the closest
var indexOfCurrent = allTimes.indexOf(currentTime);

if (indexOfCurrent == 0) { //if current is first element, nearest will be item 
//after first element
return allTimes.slice(indexOfCurrent + 1, indexOfCurrent + 2 );
}else if (indexOfCurrent == allTimes.length - 1) { //current is last one, 
//nearest will be the item before current
return allTimes.slice(allTimes.length - 2, indexOfCurrent);
}else { //if neither case above, this is where magic happens
//Find the diff between left/right adjacent element and the current element in the new sorted array 
var currTime = new Date("01/01/2018 " + currentTime).getHours();

var currTimeLower = new Date("01/01/2018 " + allTimes.slice(indexOfCurrent - 1, 
indexOfCurrent)).getHours();

var currTimeUpper = new Date("01/01/2018 " + allTimes.slice(indexOfCurrent + 1, 
indexOfCurrent + 2)).getHours();

var leftDiff  = currTime - currTimeLower;
var rightDiff = currTimeUpper - currTime;

if(leftDiff < rightDiff) {
  return allTimes.slice(indexOfCurrent - 1, indexOfCurrent);
}
else {
  return allTimes.slice(indexOfCurrent + 1, indexOfCurrent + 2);
}

};
}

console.log(findNearestTime(times, testTime));

Here is the working fiddle. 这是工作中的小提琴。 I tested with different times and it works. 我在不同的时间进行了测试,并且效果很好。 https://jsfiddle.net/b36fxpqr/13/ https://jsfiddle.net/b36fxpqr/13/

You can try this small code. 您可以尝试这个小代码。

  var timeSrc = ["10:00 PM", "08:00 AM", "11:05 AM", "12:00 AM", "01:00 AM", "12:00 PM", "03:00 AM", "07:00 AM", "06:00 PM"]; var curDate = new Date(); curDate = curDate.toDateString(); var times = timeSrc.map((t) => { return new Date(curDate + " " + t); // Make the time as a datetime with current date. }); var now = new Date(); var min = Math.abs(now - times[0]); var result = ''; //Get the difference of each time with current time. The minimum difference is the closest. for(let i = 1; i < times.length; i++) { if (Math.abs(now - times[i]) <= min) { min = Math.abs(now - times[i]); result = timeSrc[i]; } } console.log(result); 

You can try it here 你可以在这里尝试

 var arrayofDate = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM", "03:00 AM", "07:00 AM", "06:00 PM"]; var railwayTime = arrayofDate.map((data, key) => { data = parseInt(data.substr(0,2)); if(arrayofDate[key].indexOf('PM') !== -1) { data = data + 12; } return data; }); var output = closestTime(new Date().getHours(), railwayTime); document.getElementById('result').innerHTML = arrayofDate[railwayTime.indexOf(output)]; function closestTime (num, arr) { var curr = arr[0]; var diff = Math.abs (num - curr); for (var val = 0; val < arr.length; val++) { var newdiff = Math.abs (num - arr[val]); if (newdiff < diff) { diff = newdiff; curr = arr[val]; } } return curr; } 
 <div id="result"></div> 

You can also try this, But havnt tested it with more test case, correct me if i'm wrong ` 您也可以尝试这样做,但是要用更多的测试用例进行测试,如果我错了,请更正我。

var a = ["10:00 PM", "08:00 AM", "12:00 AM", "01:00 AM", "12:00 PM","03:00 AM", "07:00 AM", "06:00 PM"]
var findhour = new Date().getHours()
var ans = ""
var arrayNum = ""
for(i=0;i<a.length;i++){    
   temp = a[i].split(':')
   if (a[i].includes('PM')){
      temp1 = (12 + +temp[0])%24
      document.write(temp1+"\n")
   }else{
      temp1 = temp[0]
      document.write(temp1+"\n")
   }
   if( Math.abs(ans-findhour) > Math.abs(temp1-findhour)){
      ans = temp1
      arrayNum = i;
      console.log(ans)
   }    
}
document.write("ans  " + a[arrayNum])

` `

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

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