开发者

How to create time zone with jQuery?

How do I create a local time(time zone -> UTC + 3:30) that would show seconds with jQuery?

I do not want to use a plugin, and prefer a short code.

I do not use the following example because it gets the system time and is in javascript. It is only an example of what I want.

EXAMPLE of javascript: http://jsfiddle.net/HZmPg/

EDIT: What is your opinion about this code?

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

If this can not be done with jQuery, 开发者_开发百科what is the solution?


You could make this a function with a callback

function getTime(timezone, callback) {
        $.getJSON("http://json-time.appspot.com/time.json", {
            tz: timezone,
            callback: '?'
        },
        callback);
    });
}

$(document).ready(function(){
    var timezone = "Europe/Berlin",
        hello = function (time) {
            if (time.hour < 12) {
                alert ("Good morning in "+ timezone);
            } else {
                alert ("Good afternoon in "+ timezone);
            }
        };
    getTime(timezone, hello);
}

Or you could use deferred objects an promises to clean things up:

function getTime(timezone) {
    return $.getJSON("http://json-time.appspot.com/time.json?tz="+timezone+"&callback=?").promise();
}


$(document).ready(function(){
    var timezone = "Europe/Berlin",
        hello = function (time) {
            if (time.hour < 12) {
                alert ("Good morning in "+ timezone);
            } else {
                alert ("Good afternoon in "+ timezone);
            }
        };
    getTime(timezone).done(hello);
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜