JavaScript

Find the available time slot with JavaScript

Share your learning

This is just a fun script to find the available time slot with JavaScript.

Let’s assume we have several time slots to provide our delivery service in the area. In the time slot we have start time and end time in just a plain string. 

E.g.

var timeSlots = [
    { 'time_range' : '07am - 09am' },
    { 'time_range' : '09am - 11am' },
    { 'time_range' : '11:00 AM - 01:00 PM' },
    { 'time_range' : '10:00 PM - 11:00 PM' },
];

Now, just get the current time hours and then filter the all slots to find the available slot. First finding the start time then add 12 to it if it includes the pm. Then compare time with current time and you will get the available time slot.

var currentTime = new Date().getHours();

var newSlot = timeSlots.filter(Slots => filterSlots(Slots))

function filterSlots(Slots) {
    var slot = Slots['time_range'];

    var startTime = slot.substring(0, slot.indexOf('-'));

    var isPM = startTime.toLocaleLowerCase().indexOf('pm');

    var time = parseInt(startTime);

    if (isPM > -1) {
        time += 12;
    }
    
    if ( time >= currentTime ) {
        return slot;
    }     
   
}

console.log('newSlot :>> ', newSlot);

Output is here.

It’s really a fun to find the available time slot with JavaScript. Hope you find this article useful.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

7 months ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

7 months ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

9 months ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

9 months ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

9 months ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

9 months ago