How to determine day or night in React.js?

What is a Lifecycle Method in React.js? »

You can determine whether it’s day or night using a simple logic. Javascript returns default hours in 24 hour format. That means, any hour between 7 to 17 can be considered as day (7am to 5pm). You can consider anything else as night time. Right now, inside DayNightDisplay component, the active hour (hrs) is stored in the form of string (text). You need to convert into an integer first, so that you can compare between values. parseInt() is a method in Javascript that can convert a string value into an integer number. It accepts two parameters, the first one should be the string value and the second one should be decimal type.

const hours = parseInt(props.hours, 10);

Normally, you use base 10 numbers. Next, you need to pass this value (hours) to a function that’ll say whether it’s day or night.

For that, you’ll write a function, let’s just call it getDay(), that’ll compare and return the current day / night information.

const getDay = hours => {
    if (hours >= 7 && hours <= 17 ){
       return "It's day";
    } else {
       return "It's night!";
    }

Once you receive the information (“It’s day!” or “It’s night!”), you can store it in a variable (let’s call it rightNow) and console it out.

The complete code (DayNightDisplay.js) should look something like this:

import React from 'react';

const getDay = hours => {

    // determine whether it's day or night
    // based on hours group

    if (hours >= 7 && hours <= 17 ){
       return "It's day";
    } else {
       return "It's night!";
    }

}

const DayNightDisplay = props => {

    // convert hours from string to integer

    const hours = parseInt(props.hours, 10);

    // store the returned value in rightNow

    const rightNow = getDay(hours);

    // console out rightNow value

    console.log(rightNow);

    return <div>
       Day Night Display
    </div>;

};

export default DayNightDisplay;

Leave a Comment