Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to use the map function to see if a time is in a certain time frame with JavaScript?
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
Advertisements