获取用户时间并按本地时间减去

时间:2018-03-18 18:17:38

标签: javascript html time

我正在尝试获取用户本地时间并用我自己的时间减去它以获得时间差作为输出。

这是我到目前为止所做的:

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>

我找不到一个很好的解决方案来获取用户的确切当地时间,所以也许有人可以帮助我。

非常感谢!

1 个答案:

答案 0 :(得分:1)

简单方法:没有夏令时

与解释here一样,有一个函数getTimezoneOffset()来获取用户的时区。

但你必须知道你在女巫时区,在我的例子中你是在时区UTC + 0。

&#13;
&#13;
var myTimezone = 1;
var usersTimezone =  (new Date()).getTimezoneOffset() / 60;
var timeDifference = Math.abs(myTimezone + usersTimezone) + " hours";

document.getElementById("time").innerHTML = "Time Difference: " + timeDifference;
&#13;
<div id="time">

</div>
&#13;
&#13;
&#13;

使用夏令时计算

下面的代码也会查看他daylight saving time。 这更复杂,我使用了momentjs

看一下这篇文章: https://stackoverflow.com/a/29268535/2801860

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;