Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

javascript - How can I obtain the local time in 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.

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

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

How can I implement this in jQuery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.");
}

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);
      }
    })
});

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.

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

Hurray!, no server-side code!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...