Reputation: 147
I am trying to get the users local time and subtract it with my own to get the time difference as an output.
This is what I have so far:
var myTimezone = new Date();
var usersTimezone = 0; // UsersTimezone is missing
var timeDifference = myTimezone.getHours() - usersTimezone + " hours";
document.getElementById("time").innerHTML = "Time Difference: " + timeDifference;
<div id="time">
</div>
I couldn't find a good solution to get the exact local time of the user, so maybe someone could help me here.
Thank you very much!
Upvotes: 0
Views: 46
Reputation: 1259
Like explained here there is a function getTimezoneOffset()
to get the timezone of the user.
But you have to know in witch timezone you are, in my example you are in the timezone UTC+0.
var myTimezone = 1;
var usersTimezone = (new Date()).getTimezoneOffset() / 60;
var timeDifference = Math.abs(myTimezone + usersTimezone) + " hours";
document.getElementById("time").innerHTML = "Time Difference: " + timeDifference;
<div id="time">
</div>
The code below also looks at he daylight saving time. This is more complex and i used the momentjs for this.
Take also a look at this post: https://stackoverflow.com/a/29268535/2801860
var now = moment();
var usersOffset = now.utcOffset();
now.tz("Europe/Berlin"); // your time zone, not necessarily the server's
var myOffset = now.utcOffset();
var diffInMinutes = Math.abs(usersOffset - myOffset);
document.getElementById("time").innerHTML = "Time Difference: " + (diffInMinutes/60);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
<div id="time">
</div>
Upvotes: 1