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)
Related
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.
I've set setInterval to update my scheduler. I'm getting data from server in JSON format. But Scheduler is not getting update if I used json data, But if I put static values it works fine. Following is my code.
// It doesn't work
setInterval(function() {
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var startdt=data.processing[i].start_interval.split(",");
var endt=data.processing[i].end_interval.split(",");
var month=parseInt(startdt[1])-1;
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
var section="'"+data.processing[i].section_id+"'";
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: new Date(start),
end_date: new Date(end),
css: "inprocess",
sections: {
unit: section
}
});
scheduler.updateView();
}
Same TimeInterval with static data works fine.
// This works properly.
setInterval(function() {
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var startdt=data.processing[i].start_interval.split(",");
var endt=data.processing[i].end_interval.split(",");
var month=parseInt(startdt[1])-1;
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
var section="'"+data.processing[i].section_id+"'";
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: new Date(2013,11,29,01,00),
end_date: new Date(2013,11,29,01,30),
css: "inprocess",
sections: {
unit: 'a7b6e635-f62f-6f12-020f-52a959d1ca47'
}
});
scheduler.updateView();
}
}
},'json');
}, 5000);
}
},'json');
}, 5000);
If it works with the static data, that means that dynamic data either comes wrong or is parsed wrong on the client.
Make sure that dates and section are correct.
For example, in this code, where you collect a date string from the ajax values and check this string in console:
var start=startdt[0]+","+month+","+startdt[2]+","+startdt[3]+","+startdt[4];
var end=endt[0]+","+month+","+endt[2]+","+endt[3]+","+endt[4];
console.log(start);
console.log(end);
It would be more informative if you check the resulting date, that is passed to the scheduler API.
console.log(new Date(start));
console.log(new Date(end));
Date string might have some non-obvious error which results in invalid date object.
Secondly, the code that collects the dates is rather complex. I'd suggest to use a simplier format for transfering dates from the server(for example use unix timestamp), or to define some helper function for parsing them.
FYI, scheduler library includes scheduler.date object that defines methods for working with dates.
So you can define parse function like following. That leaves much less space for typos and accidental errors. Not quite sure that I've specified the correct date format, but you can change it if it's necessary
var parseDate = scheduler.date.str_to_date("%Y, %m, %d, %H, %i");
var start = parseDate(data.processing[i].start_interval),
end = parseDate(data.processing[i].end_interval);
One particularly suspicious line is where you retreive id of the section:
var section="'"+data.processing[i].section_id+"'";
I think you add extra quotes to the section id here. I mean var section will be equal to
"'a7b6e635-f62f-6f12-020f-52a959d1ca47'" , while in your static code you use "a7b6e635-f62f-6f12-020f-52a959d1ca47" - without extra quotes
One more thing. You call scheduler.updateView() each time timespan is added. Since this command triggers complete redraw of the calendar, it's better to call it only once when the loop is finished.
UPDATE:
here is the code sample. Didn't actually run it, but i hope it clarifies the text above
setInterval(function() {
var parseDate = scheduler.date.str_to_date("%Y, %m, %d, %H, %i");// parse string of specified format into date object
$.post('ajax_comet.php',{sectionIds:sectionIds},function (data){
if(data.processing.length>0)
{
for(var i=0;i<data.processing.length;i++)
{
var timespan = data.processing[i];
var start = parseDate(timespan.start_interval),
end = parseDate(timespan.end_interval),
section = timespan.section_id;
console.log(start);
console.log(end);
scheduler.addMarkedTimespan({
start_date: start,
end_date: end,
css: "inprocess",
sections: {
unit: section
}
});
}
//update calendar after loop is finished
scheduler.updateView();
}
},'json');
}, 5000);
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...
I'm building auction site and I'm using jQuery countdown from Keith Wood to show ending time of auctions. I need to have synchronized countdown time with server for all my clients. So far I have implemented jQuery countdown with serverSync function. It works fine, but when few seconds pass, countdown lags by 1 or 2 seconds.
How can I perfectly synchronize time for all clients, if even possible?
UPDATE: I'm also polling (500ms interval) php file, which updates all auctions (real-time effect) and in this code I also echo out new "polled" countdown from database (because when user bids in last 10 seconds of auction, countdown goes up + 10 seconds). So I think here is the problem, cause on the client side, not every poll starts in the same time, it depends when client refreshes page and so one and it affects countdown. Basically every 500ms I call in my poll.php this (which updates the countdown from database):
var syncDate = new Date("'.$formatEndDate.'");
jq("#defaultCountdown-'.$bidded_id.'").countdown("option", {until: syncDate, serverSync: serverTime});
My code so far, which lags for 1 or 2 seconds:
$(function () {
var d = new Date("'.$endingDate.'");
$('#defaultCountdown').countdown({until: d, onExpiry: endAuction,
expiryText: '<div class="bid-over">Ended</div>', format: 'HMS',
onTick: watchCountdown, serverSync: serverTime });
});
function serverTime() {
var time = null;
var url = "serverTime.php";
jq.ajax({
url: url,
async: false,
dataType: "text",
success: function (text) {
time = new Date(text);
},
error: function (http, message, exc) {
time = new Date();
}
});
return time;
}
and serverTime.php:
<?php
//This is how I get server time
header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Fri, 1 Jan 2010 00:00:00 GMT"); // Date in the past
header("Content-Type: text/plain; charset=utf-8"); // MIME type
date_default_timezone_set('Europe/Ljubljana');
$srvDate = getdate();
$d = $srvDate['mday'];
$m = $srvDate['mon'];
$y = $srvDate['year'];
$h = $srvDate['hours'];
$i = $srvDate['minutes'];
$s = $srvDate['seconds'];
$nowDate=date("$y-$m-$d $h:$i:$s");
$nowDate=str_replace("-","/",$nowDate);
echo $nowDate;
?>
I am using a jquery date picker and also setting a date through php date('Y-m-D') functions. Both of them give different date for today. Jquery picker fills the field with the date that is one day ahead of php date(). Here is the function for jquery. I need jquery to show same date for today as php.
<script type="text/javascript" charset="utf-8">
var $j = jQuery.noConflict();
$j(function()
{
// initialise the "Select date" link
$j('#date-pick')
.datePicker(
// associate the link with a date picker
{
createButton:false,
startDate: '01/01/1970',
endDate: (new Date()).asString()
//endDate:<?php echo date('y-m-d'); ?>
}
).bind(
// when the link is clicked display the date picker
'click',
function()
{
updateSelects($j(this).dpGetSelected()[0]);
$j(this).dpDisplay();
return false;
}
).bind(
// when a date is selected update the SELECTs
'dateSelected',
function(e, selectedDate, $td, state)
{
updateSelects(selectedDate);
}
).bind(
'dpClosed',
function(e, selected)
{
updateSelects(selected[0]);
}
).val(new Date().asString()).trigger('change');
var updateSelects = function (selectedDate)
{
var selectedDate = new Date(selectedDate);
if(selectedDate != "Invalid Date")
{
$j('#d').val(selectedDate.getDate());
$j('#m').val(selectedDate.getMonth()+1);
$j('#y').val(selectedDate.getFullYear());
}
}
// listen for when the selects are changed and update the picker
// default the position of the selects to today
var today = new Date();
updateSelects(today.getTime());
});
</script>
jQuery uses the client computer's date while php uses the server's date. They're basically different if you haven't set the default timezone in php. Take a look at this:
http://php.net/manual/en/function.date-default-timezone-set.php
You can set the default timezone in php.ini file located on the PHP main directory (Eg. PHP5.4)
As for the using of the server's date in the datepicker:
A quick google search lead me to this: how to display server side dates in jquery datepicker?
basically what they have done is creating a new date based on the current timestamp:
$timestamp = strtotime("2012-08-02");
minDate: new Date('<?php echo $timestamp; ?>');
DO NOT TRUST THE CLIENTS DATE AND TIME
These values can be altered at a whim.
Just use them on advisement.
Besides Javascript is there to enhance the users experience (i.e. make it more interactive). But at the end of the day you will have to pick up the pieces it you do not validate and verify the data you get from the client