how to get hosted server(LAN) datetime in javascript - php

I have a web application, where users need to get the week number in a text box. Since the users/client machines are in different time zone, they are getting the week number based on their machine datetime. How can I call the hosted server datetime in javascript. So that I can convert the date to week in common, irrespective of client machine datetime.
Hosted server is only connected in LAN, no internet access. Server Side language is PHP
Please help.

<html>
<head>
<script>
window.date = new Date(<?php echo time();?> * 1000);
window.now = new Date();
window.getTime = function() {
var n = new Date();
n = n.getTime() - window.now.getTime();
return new Date(window.date.getTime() + n);
}
</script>
And then you can access it anywhere using window.getTime(), which uses your server time + how long they have been on your page

here is an ajax-only way:
<script>
function sTime(callback) {
callback=callback||alert;
var XHRt = new XMLHttpRequest;
XHRt.onreadystatechange = function() {
if (XHRt.readyState == 4 && XHRt.status == 200) {
callback( new Date(XHRt.getResponseHeader("date")) , XHRt);
}
};
XHRt.open("HEAD", location.href, true);
XHRt.send();
return XHRt;
} /* end aHead() */
//demo to show remote and local times:
sTime(function(dt){ alert( [dt, new Date].join("\n"));});
</script>
when i ran from firebug here, seems im about 1 second behind SO...

Related

jquery countdown changes when user change its system time

i'm using jquery countdown with php. i have given an end date which is going to the countdown. my problem is lets suppose 1 hour left is showing in countdown but when a user change its system time the countdown changes. like if a user back his time 1 hour then the counter will display the 2 hours left. is there any way to get the server time for more accurate time not the user system time. please help.
how can i get server time not user system time?
below is my jquery code
if($(pluginsArray[6]).length){
$(pluginsArray[6]).each(function(){
var $this = $(this),
dateObj = $this.data();
var finalDate = new Date(dateObj.year, dateObj.month, dateObj.day, dateObj.hours, dateObj.minutes);
$this.countdown({
timezone: +4,
until : finalDate,
expiryText: '<div class="over">Closed.</div>',
onExpiry : function(){
setTimeout(function( ) { location.reload(); }, 5000);
},
format :'DHMS',
layout : '<b>{dn}</b> <span class="fs_medium d_inline_b m_right_5">days</span> <b>{hn}</b> <span class="fs_medium d_inline_b m_right_5">hrs</span> <b>{mn}</b> <span class="fs_medium d_inline_b m_right_5">min</span> <b>{sn}</b> <span class="fs_medium">sec</span>'
});
});
}
and here is what i did in php
<div class="countdown color_redc d_inline_m fs_large second_font lh_small f_xs_20" style="font-size:26px;" data-year="<?= $aDate[0] ?>" data-month="<?= ($aDate[1] - 1) ?>" data-day="<?= $aDate[2] ?>" data-hours="<?= $aDate[3] ?>" data-minutes="<?= $aDate[4] ?>"></div>
Solution without PHP
What you can do, without coding any server side is using a public API to get current time.
Found a similar topic on StackoverFlow : Free Rest API to get current time as string (timezone irrelevant)
TimezoneDb provides a free API: http://timezonedb.com/api
GenoNames also has a RESTful API available to get the current time for
a given location: http://www.geonames.org/export/ws-overview.html.
You can use Greenwich, UK if you'd like GMT.
GenoNames looks to be US only, TimezoneDb works you just need to register for a free public key.
Few people recommend timeapi.org but looks like they do not accept CROSS-DOMAIN request in Ajax, and the exemple they provide is no longer available.
Solution with PHP and jQuery Countdown configuration
Also you can ask jQuery CountDown to synchronyze with your server using serverSync option
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
PHP file : serverTime.php
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
BUT
Keep in mind your user will always be able to change your code and fake it ... so if you need to implement some security this is not enough and you will need to code some backend stuff.

Uncaught ReferenceError: jquery is not defined in Wordpress

Can anyone help me out from this issue. I have added a JS to my WordPress site externally. It doesn't produce the output and throws an error in the following code.
Please help me out and get over it.
var clock;
jquery(document).ready(function() {
var currentDate = new Date();
// Set some date in the past. In this case, it's always been since Jan 1
var pastDate = new Date(currentDate.getFullYear(), - 3, 4, 3);
// Calculate the difference in seconds between the future and current date
var diff = currentDate.getTime() / 1000 - pastDate.getTime() / 1000;
clock = jquery('.clock').FlipClock(diff, {
clockFace: 'MinuteCounter'
});
});
JavaScript is case sensitive. Use jQuery instead of jquery:
jQuery(document).ready(function() {
.
.
.
clock = jQuery('.clock').FlipClock(diff, {
clockFace: 'MinuteCounter'
});
});

Retrieve firebase server time without setting it first

Is there a way to obtain the server time without having to first set it? For example, I can simply do:
curl -X PUT -d '{".sv": "timestamp"}' https://SampleChat.firebaseIO-demo.com/servertime.json
which will return the server time, but this sets the value servertime within my firebase instance. I should note that I'm using the REST API.
You can retrieve the server time without writing it by using .info/serverTimeOffset:
var fbRef = new Firebase(URL);
var getServerTime = (function(ref) {
var offset = 0;
ref.child('.info/serverTimeOffset').on('value', function(snap) {
offset = snap.val();
});
return function() {
return Date.now() + offset;
}
})(fbRef);
var now = getServerTime();

show dynamic time with javascript

I want to show the time which I have in my php variable with the help of Javascript
I am coding an online exam module, where I want to display the total elapsed time
say for example
$time_elapsed // contains the time taken till now from the start of the exam
And if I got a div say,
<div id="time"></div>
how can I show the dynamic running time with starting from $time_elapsed after load the window for each question
Please if you guys have an answer for this..
Thanks
hi you can use the following code for the purpose
the javascript will be:
var Timer;
var TotalSeconds,TotalMins, secs;
var elapsedtime ;
function CreateTimer(TimerID, Time) {
Timer = document.getElementById(TimerID);
TotalSeconds = Time;
elapsedtime = 0
time = Time
secs = TotalSeconds%60;
TotalMins = Math.floor(TotalSeconds/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
function Tick() {
if(TotalSeconds-elapsedtime>0)
{
elapsedtime += 1;
secs = (elapsedtime%60)-60;
TotalMins = Math.floor(elapsedtime/60)
UpdateTimer()
window.setTimeout("Tick()", 1000);
}
else
alert("time up")
}
function UpdateTimer() {
Timer.innerHTML = TotalMins + ":" + secs;
}
nw create a html div where you want to show the running time.
Html:
<div id='timer' />
<script type="text/javascript">window.onload = CreateTimer("timer", 5);</script>
give parameter the time limit. it will alert after time finishes.
and to get time after refresh of the page use html5's sessionStorage
visit Html5 Storage Doc to get more details. using this you can store intermediate values temporaryly/permanently locally and then access your values
for storing values for a session
sessionStorage.getItem('label')
sessionStorage.setItem('value', 'label')
or store values permanently using
localStorage.getItem('label')
localStorage.setItem('value', 'label')
So you can store (temporarily) form data between multiple pages using html5 storage objects
This is how to display dynamic time. To use other php based starting time replace the line time0 = new Date(); by time0 =<?php echo $startTime;?>; which should be in ms since the epoch.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>elapsed time demo</title>
<script type="text/javascript">
var time0;
function initTime() {
time0 = new Date();
window.setInterval("updateTime()", 1000);
}
function updateTime() {
var timeNow = new Date();
var deltas = (Number(timeNow) - Number(time0))/1000;
var deltah = ("0"+String(Math.round(deltas / 3600))).substr(-2);
deltah = deltah.substr(-2);
deltas %= 3600;
var deltam = ("0"+String(Math.round(deltas / 60))).substr(-2);
deltas = ("0"+String(Math.round(deltas % 60))).substr(-2);
document.getElementById("timedisplay").firstChild.data=deltah+":"+deltam+":"+deltas;
}
</script>
</head>
<body onload="initTime();">
<div> elapsed time <span id="timedisplay">00:00:00</span></div>
</body>
</html>​
Your php code should return the time elapsed at the point of loading the page, however, javascript will then take over and increment that time as time passes.
You can send the parameter to your JavaScript function which is display time
function display_time(int time)
{
//your code for further integration
}
You can send the parameter to JavaScript function using following way
//call the function at the time display time
display_time(<?php echo $time_elapsed ?>)

Jquery Countdown Server sync issue

I'm trying to create a countdown for an event. I'm using Jquery Countdown
I have this code:
$(function () {
var fecha = new Date("July 30, 2011 00:00:00");
$('#defaultCountdown').countdown({
until: fecha,
format: 'DHMS',
expiryUrl: "http://www.google.com",
serverSync: serverTime,
timezone: -4
});
});
function serverTime() {
var time = null;
$.ajax({
url: 'serverTime.php',
async: false,
dataType: 'text',
success: function (text) {
time = new Date(text);
},
error: function (http, message, exc) {
time = new Date();
}
});
return time;
}
The script is working fine, but when I try to change the clock date, the countdown changes.
Any idea why?
I imagine you created the serverTime.php file on your server?
http://keith-wood.name/countdown.html
Tab Timezones has the PHP code you'll need to add to serverTime.php for your script to use that. Also may want to fully qualify that to something like url: 'http:yourdomain.com/serverTime.php' But using that it should use your server time not your local PC time. If your server is on your local PC, then well... it would change.
I went to their site, with their example, and changing my system time affects their countdown as well. Their code relies on local system times.
What I see when you get the server time form the ajax call, it is not creating the JavaScript date object.
I searched and below worked for me.
// Split timestamp into [ Y, M, D, h, m, s ]
var t = "2010-06-09 13:12:01".split(/[- :]/);
// Apply each element to the Date function
var d = new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
alert(d);
// -> Wed Jun 09 2010 13:12:01 GMT+0100 (GMT Daylight Time)

Categories