Your code has a bug: d.getHours()
will return a plain number. Calling toLocaleString
on that number calls Number.prototype.toLocaleString
, which:
returns a string with a language-sensitive representation of this number.
It does not do anything with timezones; the second parameter does not recognize a timeZone
property. For example, where I am now, .getHours()
returns 9
, and (9).toLocaleString('en-US', { timeZone: 'America/New_York' })
returns "9"
.
On your server, to retrieve the hours in a particular timezone, one method would be to call toLocaleString
on the date object itself with the appropriate timezone, then extract the number of hours from that string:
const timeString = new Date().toLocaleString('en-US', { timeZone: 'America/New_York' });
const [, hours, ampm] = timeString.match(/ (\d+).* ([AP]M)/);
console.log('In NY, it is:', hours, ampm);
Other issues:
- Since it's 2020, best to prefer at least 2015+ syntax, which should not be an issue since the code is running on the server. (Among other things, being able to use
const
is wonderful)
- You initialize
f
to the empty string, but then you reassign it immediately; the empty string is not used, so there's no point to assigning it.
- Or, even better: since you want to conditionally assign a value to
f
depending on the number of hours, it would be more appropriate (and shorter) to use the conditional operator:
const f = Number(hours) < 9 && ampm === 'AM'
? 'shipping available'
: 'shipping unavailable';