How can i calculate local time in node js

Tags: ,



I want to do send a automated email from by backend with a date stored in my db.

But the db consists of UTC date.

I wanted to convert it to local time for the user sending the email.

What i thought of was, i can send a offset while making the API call. i.e new Date().getTimezoneOffset() and i add or subtract this to the UTC date stored in the db.

What i am not sure about is how do i make this calculation and also i am not sure if this approach will work.

Answer

Your approach is fine actually. You can get time-zone difference on front-end side, and pass it to backend-end through request.body.

var offset = new Date().getTimezoneOffset();
console.log(offset);

The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, if your time zone is UTC+10 (Australian Eastern Standard Time), -600 will be returned. Daylight savings time prevents this value from being a constant even for a given locale.

You can get local time on backend-side in this way.

const offset = 540;
var date = new Date();
date.setMinutes(date.getMinutes() - offset);
console.log(date);


Source: stackoverflow