Last Updated: August 18, 2023
·
46.74K
· declandewet

Convert Node.js "new Date()" to user's local timezone on the client

This is a snippet I have become very fond of. Assuming your node.js server simply sets a time property to new Date() and makes that property available to the client, you can convert it to the user's local time zone using client-side code like this:

var toLocalTime = function(time) {
  var d = new Date(time);
  var offset = (new Date().getTimezoneOffset() / 60) * -1;
  var n = new Date(d.getTime() + offset);
  return n;
};

Couple that with moment.js and all your time-related issues are but a mere memory of a long and forgotten pain.

3 Responses
Add your response

So right now I use:
client.sendMSG( new Date().toLocaleTimeString() + ' : ' + message.utf8Data );

How can I use your function with what I have to get the local time?

over 1 year ago ·

This is wrong. getTimezoneoffset() returns the offset in minutes. This would basically turn your minutes into hours and then subtract that from milliseconds which would not do anything correct. Use this instead:

const toLocalTime = (time) =>{ 
    let d = new Date(time); 
    let offset = (new Date().getTimezoneOffset() * 6000); 
    return new Date(d.getTime() + offset);
};
over 1 year ago ·

Working:
const toLocalTime = (time: Date) => {
let d = new Date(time);
let offset = (new Date().getTimezoneOffset() * 60000);
if (offset < 0)
return new Date(d.getTime() - offset);
else
return new Date(d.getTime() + offset);
};

over 1 year ago ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip