Reputation:
A business requirement of a project is as follows:
The user needs to view historic dates based on his local time zone. For now, we store two dates in the database: UTC and the local time. The user needs to view the date in the (historic) time zone.
Example:
Database values: 2017-10-25T12:00:00 (UTC), 2017-10-25T09:00:00 (Date of registration).
From these values, we want the user to view the date in his time zone.
2017-10-25T12:00:00 (UTC) to CEST (time zone offset +0200) => 2017-10-25T14:00:00.
However, when the user views the same date on a date where summer time does not apply, the user will see 2017-10-25T13:00:00 because CET is +0100.
I'm looking for a way in which it is possible to get the offset from UTC for the user's locale on the UTC date.
In short: get the UTC offset for a historic date in the user's local time zone.
EDIT: libraries like Moment.js and Moment_timezone.js are accepted!
Upvotes: 1
Views: 655
Reputation:
Thank you all for your comments. I think I got it by doing like so:
var oUTC = moment(new Date(2015, 7, 25, 12, 0, 0, 0));
var oRecordedDate = moment(new Date(2015, 7, 25, 13, 0, 0, 0));
//step 1: calculate historic offset with DB values
var iDBOffset = oUTC.diff(oRecordedDate);
//step 2: calculate historic offset from UTC in user's locale
var oHistoricDate = oUTC.clone().tz(moment.tz.guess());
var iHistoricOffset = Math.abs(oHistoricDate.utcOffset() * 60 * 1000);
//step 3: calculate total offset
var iTotalOffset = iDBOffset - iHistoricOffset;
//step 4: resulting date object
var oDate = new Date(oRecordedDate.valueOf() - iTotalOffset);
console.log(oDate.toString());
Upvotes: 0
Reputation: 241525
I'm looking for a way in which it is possible to get the offset from UTC for the user's locale on the UTC date.
var dt = new Date("2017-10-25T12:00:00Z");
var offset = dt.getTimezoneOffset();
(note the Z
at the end)
Though really, one wonders why you need the offset at all. The local time is already represented by the Date
object in dt
.
If you want to do this with Moment, then you can do:
var m = moment("2017-10-25T12:00:00Z");
Or if you don't want to add the Z
then create the Moment object like so:
var m = moment.utc("2017-10-25T12:00:00").local();
You can format the moment from there, or call m.utcOffset()
if you like.
You don't need Moment-timezone, unless you intend to reflect some time zone other than the user's local time zone.
Upvotes: 1