简体   繁体   English

使用JavaScript通过IP地址获取用户本地时间?

[英]Get user local time by ip address with JavaScript?

I'm trying to get time of day for someone visiting my site. 我正在努力吸引访问者访问我的网站。 Seems easy enough, but the tricky part is that people may be traveling from other timezones and not changing their system clock. 似乎很容易,但是棘手的部分是人们可能正在从其他时区旅行而未更改他们的系统时钟。 Using the below: 使用以下内容:

  var d = new Date();
  var currentTime = d.getHours();
  console.log( currentTime );

  if(currentTime < 12){
    var tod = "morning";
  }else if(currentTime >= 12 && currentTime <= 17){
    var tod = "afternoon";
  }else{
    var tod = "evening";
  }
document.write("hour of day is: "+currentTime);
console.log("Time of day is: "+tod );

I was able to detect local system time. 我能够检测到本地系统时间。 For example, if my clock says 7:06 AM, then the variable currentTime will be 7. This works based on the system clock. 例如,如果我的时钟说7:06 AM,则变量currentTime将为7。这基于系统时钟。 So if I change my time zone to Eastern, currentTime will be 10 instead of 7. The problem is I'd like to detect the time of day where the user is actually sitting at that moment. 因此,如果我将时区更改为“东部”,则currentTime将是10而不是7。问题是我想检测用户当时实际坐在哪一天的时间。 So if I'm on the East coast and my system clock says 7AM, I still want to show the user a 10. I want to detect the hour of day it actually is where the user is by IP address. 因此,如果我在东海岸,并且系统时钟显示为7AM,我仍然想向用户显示10。我想通过IP地址检测用户实际所在的时间。 I have found a way to collect IP address, but not sure how to use it to get the local time. 我已经找到一种收集IP地址的方法,但是不确定如何使用它来获取本地时间。

If there is another way I am also open to that as well. 如果还有另一种方法,我也愿意接受。 Thanks. 谢谢。

Some might suggest getting it from the server, but I am using marketing cloud and there does not appear to be a way to do it. 有人可能建议从服务器上获取它,但是我正在使用市场营销云,但似乎没有一种实现方法。 I've used the available AmpScript functions and they do not work as I would have expected. 我已经使用了可用的AmpScript函数,但它们无法正常运行。

Use any API that will respond with user's timezone. 使用任何会响应用户时区的API。 For example this one: 例如这个:

http://ip-api.com/json

And calculate user's time basing on it. 并据此计算用户的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM