Hkm Sadek
Hkm Sadek

Reputation: 3209

Time zone offset showing incorrect date and time

I am trying to show time based on user local time zone. Server saves time to utc.

So, I have a date-time saved in my database.

2018-10-03 05:55:51 // my server is digital ocean

So now I am trying to console user local time. My time zone is set to Sylhet Bangladesh Time offset is -360

var offset = new Date().getTimezoneOffset();
console.log(offset) // offset is -360
var testDateUtc = moment.utc("2018-10-03 05:55:51");
var localDate = moment(testDateUtc).utcOffset(offset);
console.log(localDate.format("YYYY-DD-MM hh:mm:ss"));

The above code prints incorrect date but correct time. 2018-02-10 11:55:51 the date is wrong.

I then changed my mac's time zone to Dubai which is 2 hours different then my country

For dubai the offset is -240 and it shows time 2018-03-10 01:55:51 this mean the date is correct but time is not correct.

Please help. Thank you.

EDIT It works for most of the countries I tested like this offset = Math.abs(offset) so it always make it positive

Upvotes: 1

Views: 709

Answers (1)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241959

You do not need to think about the offset. Moment can do that for you:

moment.utc("2018-10-03 05:55:51").local().format()

Also, keep in mind that when you asked for the offset in your code, you asked for the current offset, which may or may not be the offset in effect at the time you're converting. See "Offset != Time Zone" in the timezone tag wiki.

Upvotes: 1

Related Questions