2

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

9
  • 1
    Wow...I know that UTC is the French version and in English it's "coordinated universal time" but this might be the first time I've seen CUT being used to refer to it. Commented Mar 26, 2021 at 7:31
  • 2
    Also, why send the date formatted from the server? Usually the server sends timezone agnostic date (UTC/Unix timestamp) and the client formats it accordingly. Commented Mar 26, 2021 at 7:33
  • @VLAZ the CUT was typo Commented Mar 26, 2021 at 7:34
  • Did you try new Date().toUTCString() ? Commented Mar 26, 2021 at 7:35
  • @Anurag yeah and it returns "TypeError: date.toUTCString is not a function" Commented Mar 26, 2021 at 7:35

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.