Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ใช้ map() ตรวจสอบเวลาอยู่ในช่วงที่กำหนดใน JavaScript

แยกเวลาเริ่ม/จบจากสตริง "5 PM - 11 PM" แปลงเป็น 24 ชม. เปรียบเทียบกับเวลาปัจจุบัน

ตัวอย่างโค้ด

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

function timeToReadSubjectName(scheduleDetails) {
    var currentTime = new Date().getHours(); // 0-23
    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));

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo128.js)

ผลลัพธ์ตัวอย่าง

The Subject which you need to read in this time=JavaScript