Reputation: 33
Im currently testing out running a server with routes etc. and am trying to display the date of the previous person to request that route. Usually when i use the new Date() object i get it in my local time, but for some reason it is displaying it in UTC (coordinated universal time) and im not sure how to change it.
my code is
var date;
var dateArr = [];
var counter = 0;
router.get('/last.txt', function(req, res) {
counter++;
date = new Date().toString();
dateArr.push(date);
if (counter == 1) {
res.send("");
} else {
res.send(dateArr[counter-1]);
}
});
but i keep receiving the date in the format:
Fri Mar 26 2021 07:24:50 GMT+0000 (Coordinated Universal Time)
Any advice would be appreciated!
EDIT: I live in Australia so i think it usually outputs in AEDT
Upvotes: 2
Views: 182
Reputation: 1073988
It would appear that UTC is the timezone in place for the server where this code is running. That's fine, you can convert that to the local timezone on the client quite easily. Rather than using toString
, though, I would store either the Date
object, or its time value (the result of .valueOf()
), or the result of .toISOString()
and then send either the time value (a number) or the ISO string value to the client. That way, you're not relying on the timezone of the server. When you pass either of those (the time value or the ISO string) into new Date
on the client site, the resulting Date
will have the same date/time, but because it's operating in the client's timezone, its local time formatting methods like toString
, getFullYear
, etc., will use the local timezone of the client.
E.g., change toString
to (for instance) toISOString
in your code, and on the client:
const dt = new Date(theStringFromTheServer);
console.log(dt.toString()); // Will use the client's timezone to show the date/time
Upvotes: 1