Home > Enterprise >  setHours method not working as expected in React
setHours method not working as expected in React

Time:11-10

I am trying to change the hours in my React app using the setHours method:

function App() {
    let currHour = new Date().setHours(15);

    return (
    <div>
        <h1>{currHour}</h1>
    </div>
    );
}

Instead of getting 15 as my output I am getting is: 1667813785897.

How I am getting this unexpected output?

CodePudding user response:

Couple things, currHour is a Date object, so rendering it is going to just call the toString method, which is just going to output the milliseconds or something. If you want 15 then you'll want to render currHour.getHours(). Also, currHour is going to be set to new Date().setHours(15) every time App is rendered, which is probably undesirable. Maybe it should be state? Or in a ref? I'm not sure what your use case is.

CodePudding user response:

If we look at the enter image description here

so the result you are receiving is actually expected. Let's see a snippet which should prove to be helpful:

let dt = new Date();
console.log(`The current date is ${dt}`);
console.log(`Hours before setting the hours to 15 were ${dt.getHours()}`);
let millisecondsSince1970 = dt.setHours(15);
console.log(`After setting the hours to 15, the modified date is ${dt}`);
console.log(`Hours after setting the hours to 15 are ${dt.getHours()}`);
console.log(`Milliseconds since January 1st 1970 00:00:00 are ${millisecondsSince1970}`);
console.log(`Milliseconds since January 1st 1970 00:00:00 converted back to Date is ${new Date(millisecondsSince1970)}`);

As you can see, we can get both the dates and the hours

So, instead of getting the result of setHours you can do something like this to set the hours to 15 and return them:

let currDate = new Date();
currDate.setHours(15);
let currHours = currDate.getHours();

or, if you did not even want to set the hours, then you can simply say

let currHours = new Date.getHours();
  • Related