如何在 jQuery 中获取本地时间? [英] How can I obtain the local time in jQuery?

查看:16
本文介绍了如何在 jQuery 中获取本地时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery,我需要获取德国的当地时间.

I am using jQuery and I need to get the local time for Germany.

从任何国家/地区访问我网站的任何人都应该能够知道德国的时间.

Anyone coming to my website from any country should be able to know what time it is in Germany.

如果时间在 0:00 到 12:00 之间,我需要发出警报:早上好".

If the time is between 0:00 and 12:00 I need to make an alert reading: "Good Morning".

如果时间在 12:00 到 17:00 之间,我需要提醒阅读:下午好".

If the time is between 12:00 and 17:00 I need to make an alert reading: "Good Afternoon".

如何在 jQuery 中实现这一点?

How can I implement this in jQuery?

推荐答案

可以通过获取客户端本地时区偏移量得到 GMT 时间,然后加上德国时区的偏移时间(中欧时间 GMT+1):

You can get the local timezone offset of the client to get the GMT time and then add the offset hours of the Germany timezone (Central European Time GMT+1):

function getDate(offset){
  var now = new Date();
  var hour = 60*60*1000;
  var min = 60*1000;
  return new Date(now.getTime() + (now.getTimezoneOffset() * min) + (offset * hour));
}

//...

var dateCET = getDate(1); // Central European Time is GMT +1

if (dateCET.getHours() < 12) {
    alert ("Good morning.");
} else {
    alert ("Good afternoon.");
}

更新:我同意@Josh,上面的代码完全依赖于客户端.让我们努力做得更好:

Update: I agree with @Josh, the above code is completely client dependent. Let's try to do it better:

$(document).ready(function(){
  var timezone = "Europe/Berlin";
  $.getJSON("http://json-time.appspot.com/time.json?tz="+timezone+"&callback=?",
    function(data){
      if (data.hour < 12) {
        alert ("Good morning in "+timezone);
      } else {
        alert ("Good afternoon in "+timezone);
      }
    })
});

我们现在利用 JSONP 来做 Cross-域请求到 jsontime 服务器,该服务器公开了一个完整的 JSON API 来查询时间和时区信息.

We are now taking advantage of JSONP to do Cross-Domain requests to the jsontime server, this server exposes a complete JSON API to query time and timezone information.

您可以在此处使用代码,还可以探索 JSONP API 这里.

You can play with the code here and you can explore the JSONP API here.

万岁!没有服务器端代码!

Hurray!, no server-side code!

这篇关于如何在 jQuery 中获取本地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆