Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current Date from Internet via JavaScript

Tags:

javascript

I have this function:

function fun_voting_started(){
var now = new Date();
var now_date = now.getDate();
var now_month = now.getMonth(); now_month++;
var now_year = now.getFullYear();
var now_hours = now.getHours();
var now_min = now.getMinutes();
var now_sec = now.getSeconds();
var voting_started = now_year + "-" + now_month + "-" + now_date + " " + now_hours + ":" + now_min + ":" + now_sec; 
return voting_started;
}

This function loads Date from computer, but sometimes user have other Date than is current. How can I get the current Date from Internet?

like image 482
user3357400 Avatar asked May 21 '14 12:05

user3357400


1 Answers

Answering this purely from a PoC perspective to the question title "How to get current Date from Internet via JavaScript", irrespective of how useful or useless it might be.

You can get the time from an Internet Time Server (or any server for that matter) which publishes an API for you to do that. You may search the web to find one.

For example, (this) and (this)

These services support JSONP for AJAX callback with Javascript.

Demo: http://jsfiddle.net/abhitalks/n66eP/

JS:

$.ajax({
    dataType: 'jsonp',
    url: 'http://timeapi.org/utc/now.json',
    success: function (result) {
        alert(result.dateString);
    }
});

The service returns an object with date string. Just need to access the dateString property here.

like image 128
Abhitalks Avatar answered Oct 17 '22 22:10

Abhitalks