0

I am using Node.js and Heroku for my server-side and my request responses are based on the given time of the day. So I am trying to get the hours and minutes every time the user makes a request as the following:

app.post('/heroku-url', (request, response, next)=>{
  const estTime = new Date().toLocaleString('en-US', {hour12:false, timeZone:"America/New_York"});
  const day = new Date(estTime);
  
  console.log("My Hours is "+ day.getHours())
})

However, this logs NaN in the console. If I move it outside of the request, it returns the hour from which the dynos got restarted which is not what I want. Any help with this issue?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Babou
  • 151
  • 1
  • 12
  • 3
    So `day` is an invalid date because `estTime` isn’t a date string in the expected format. I’m not sure why you _format_ the string (using `toLocaleString`) at all here. What purpose does this serve? – Sebastian Simon Nov 01 '22 at 05:12
  • I wanted to manage the time on EST given that Heroku default time is UTC. – Babou Nov 02 '22 at 11:56
  • See [Javascript date format like ISO but local](/q/12413243/4642212) and [How to initialize a JavaScript Date to a particular time zone](/q/15141762/4642212). – Sebastian Simon Nov 02 '22 at 18:04

1 Answers1

1

This is all you need, the estTime is completely useless and makes the Date object invalid.

app.post('/heroku-url', (request, response, next)=>{
  const day = new Date();
  
  console.log("My Hours is "+ day.getHours())
})
Ammar Ahmed
  • 344
  • 3
  • 11
  • Yes this works what confuses me is that what I initially had was valid code as long as I do not put it inside the http request – Babou Nov 02 '22 at 11:57