Organize and locate the nearest time from the present moment

I have an array of different 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"]

My goal is to arrange them in order and determine the time closest to the current time. For instance, if it is now 05:00 PM, the expected response from the above array should be 06:00 PM.

I'm currently using the following code to sort the array:

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

Any suggestions on how to improve the sorting method and efficiently find the nearest time based on the current time would be greatly appreciated. Thank you.

Answer №1

To find the most appropriate hour, calculate the difference between the current hour and array hours in a separate array. Sort this array in ascending order and retrieve the first element to determine the most suitable hour.

Below is an example snippet for reference:

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);

For a demonstration, check out the working fiddle here: https://jsbin.com/zojawagiyi/6/edit?js,console

Answer №2

Give this code a go, I believe it will get the job done.

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));

Check out the jsbin link here https://jsbin.com/piwuziqeje/edit?js,console

Answer №3

If you're looking for a solution, the following code snippet can help you sort an array and then identify the nearest date from the current time.

To begin, the code combines the current time with the array, and then proceeds to determine the nearest date available.

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);
}

Answer №4

Feel free to experiment with this concise code snippet.

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); // Create datetime using current date.
});
var now = new Date();
var min = Math.abs(now - times[0]);
var result = '';
// Find the closest time by comparing differences with current time.
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 test it out here

Answer №5

My approach to solving this problem differs from what has been shared here previously. While it may be slightly longer, I believe it offers a clearer explanation of the logic behind the code. The functionality has been verified and you can see the results in the provided fiddle. Below is the code snippet:

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));

To view the working example along with different test cases, please refer to the following fiddle link: https://jsfiddle.net/b36fxpqr/13/

Answer №6

var scheduleOfTrains =  ["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 trainTimings = scheduleOfTrains.map((time, index) => {
time = parseInt(time.substr(0,2));
if(scheduleOfTrains[index].indexOf('PM') !== -1) {
time = time + 12;
}
return time;
});

var closestTrainTime = findClosestTime(new Date().getHours(), trainTimings);

document.getElementById('result').innerHTML = scheduleOfTrains[trainTimings.indexOf(closestTrainTime)];

function findClosestTime (currentHour, array) {
var current = array[0];
var difference = Math.abs(currentHour - current);
for (var value = 0; value < array.length; value++) {
var newDifference = Math.abs(currentHour - array[value]);
if (newDifference < difference) {
difference = newDifference;
current = array[value];
}
}
return current;
}
<div id="result"></div>

Answer №7

If you haven't tested this with more test cases, please correct me if I'm wrong:

let 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"];
let currentHour = new Date().getHours();
let closestTime = "";
let closestTimeIndex = "";
for(let i=0; i<times.length; i++){    
   let temp = times[i].split(':');
   let formattedHour = 0;
   if (times[i].includes('PM')){
      formattedHour = (12 + +temp[0]) % 24;
      console.log(formattedHour);
   }else{
      formattedHour = temp[0];
      console.log(formattedHour);
   }
   if(Math.abs(closestTime-currentHour) > Math.abs(formattedHour-currentHour)){
      closestTime = formattedHour;
      closestTimeIndex = i;
      console.log(closestTime);
   }    
}
document.write("Closest time: " + times[closestTimeIndex]);

`

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to collapse and expand individual rows within the Material-UI DataGrid component?

Is there a way to create expand-collapse functionality for each row in Material-UI DataGrid? While I understand that we can achieve this with TableRow and manual rendering (Collapsible table), I am wondering if it is possible within the DataGrid component ...

Having trouble assigning the current page in NextJS navigation

I have a unique setup for my navigation system in my NextJS project: const menu = [ { name: 'Home', href: '/home', icon: HomeIcon, current: true }, { name: 'About', href: '/about', icon: InfoIcon, current: fa ...

What steps should I take to address a problem involving a callback function?

I'm currently working on an application that aims to connect users with friends based on specific questions they answer. However, I keep encountering an error message stating "TypeError [ERR_INVALID_CALLBACK]: Callback must be a function" when the cod ...

AngularJS fails to prioritize the following element

Here is my HTML code: <div ng-app="app"> <form> <div class="form-group"> <label >Username</label> <input focus type="text" class="form-control" id="loginUserName" ng-model="userForm.crn" required/> ...

Exploring the power of using Play JSON library in Scala to deserialize JSON while ignoring any unknown fields

When working with a JSON response in Scala, I need to parse it to a case class but only want to consider specific fields from the JSON data. For instance: If the JSON object returns {id: XYZ, name: ABC, ... // more fields } I am interested in only the fiel ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

How about placing a particle on the top layer of a mesh at a random location?

I am struggling to place a particle on the top side of a custom mesh using Three.js. Most tutorials I've come across only demonstrate adding particles to cubes or spheres, leaving me with no solution for my unique shape. How can I successfully positio ...

python transform a single JSON format into a hierarchical structure

Is there a way to convert JSON data into a specific target format by extracting unique country names and grouping all entries with the same country name together? The dataset contains 50 thousand entries. The original JSON structure is as follows: [ ...

How does the scope of functions included in files differ between Javascript and PHP?

Last month, I inquired about a PHP issue involving calling a function in one include file that is defined in a later include file. This problem came up during the conversion of an ASP site to PHP, and now it's resurfacing. It seems like Javascript and ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

The 'disable' prop in Material UI textfield fails to update after the initial change

Currently, I am working on a program that involves radio switches, each representing a different boolean value. This program aims to toggle the 'disable' property of a textfield based on the boolean value selected by the user. The issue I am faci ...

What is causing the code behind to reject the href with 'aspx' in the anchor tag?

I am currently working on implementing a calendar control that will display Today's Due and Overdue items in separate accordion sections when a date is selected. To achieve this, I have written the necessary code in the back end and used a style.css f ...

Combining elements of an array using the merge() function within a while() loop and then extracting those values in array format using $row['field_name']

My query is being processed here. The $merge variable holds the specific structure I require. I aim to convert the $merge data into an array and extract each value as $row[0], $row[1], $row[3], etc... outside of the while loop. while ($row = mysql_fetch_ ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Having trouble accessing properties from null object (specifically 'map') in React

I encountered an issue where my search bar was supposed to display some results but instead it showed the following error message: Cannot read properties of null (reading 'map') // import axios from "axios"; import React, { useEffect, ...

What could be causing the MySQL query to return null results in the Android application?

I am facing an issue with reading data from my database and using it in my application. I have written a PHP script to act as a web service to connect to my MySQL database, but I am encountering an exception while parsing the JSON data. When I tried to rem ...

Using observables rather than promises with async/await

I have a function that returns a promise and utilizes the async/await feature within a loop. async getFilteredGuaranteesByPermissions(): Promise<GuaranteesMetaData[]> { const result = []; for (const guarantees of this.guaranteesMetaData) { ...

Utilizing Regular Input with Material-UI's Autocomplete Feature

Is there a way to replace TextField with a regular input in an Autocomplete? ...

Is there a way to keep the selected option in handlebar permanently, even after multiple page refreshes?

I am having trouble implementing the drop-down menu option in handlebars using jQuery. Therefore, I have opted to use the select-options menu instead. Here is the code snippet: <select name="sources" id="sources" class="custom-s ...

Converting Python Class Structures into JavaScript

I currently have some Python classes structured like this: class Customer { constructor(name, fullName, gender, age, instruments, paid) { this.name = name; this.fullName = fullName; this.gender= gender; this.age= age; ...