DISABLE ADBLOCK

ADBlock is blocking some content on the site

ADBlock errore
Results found: 

Question

How to use the map function to see if a time is in a certain time frame with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say, we have subject records with the time when we are planning to study them −

const scheduleDetails = [
   { subjectName: 'JavaScript', studyTime: '5 PM - 11 PM' },
   { subjectName: 'MySQL', studyTime: '12 AM - 4PM' }
]

Here is how we can use the map(). Following is the code −

Example

const scheduleDetails = [
   { subjectName: 'JavaScript', studyTime: '5 PM - 11 PM' },
   { subjectName: 'MySQL', studyTime: '12 AM - 4PM' }
]
function timeToReadSubjectName(scheduleDetails) {
   var currentTime = new Date().getHours();
   let result = '';
   scheduleDetails.map(obj => {
      const hourDetails = obj.studyTime.split(' ');
      const firstCurrentTime = hourDetails[1] === 'PM' ? 12 : 0;
      const secondCurrentTime = hourDetails[4] === 'PM' ? 12 : 0;
      if (currentTime > (+hourDetails[0] + firstCurrentTime) &&
      currentTime < (+hourDetails[3] + secondCurrentTime)) {
         result = obj.subjectName;
      };
   })
   return result;
}
console.log("The Subject which you need to read in this
time="+timeToReadSubjectName(scheduleDetails));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo128.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo128.js
The Subject which you need to read in this time=JavaScript
raja
Published on 10-Sep-2020 10:45:41
Advertisements

If you like, leave us your opinion

Was the article helpful and is it translated correctly?

Not affiliated with Tutorialspoint