Time count down like www.bidhere.com - php

Can anybody please suggest to me how I can create a time countdown like www.bidhere.com.
what are the techniques used on that. e.g jQuery or cronjob ?
Thanks.

You can use javascript to achieve that affect
Markup
<body>
<div id="countdown"></div>
</body>
Javascript
function countdown(remain) {
var countdown = document.getElementById("countdown"),
timer = setInterval( function () {
countdown.innerHTML = (remain%60 < 10 ? "0": "") + remain %60;
if (--remain < 0 ) { clearInterval(timer); }
},1000);
}
countdown(20);

<span class="countdown" rel="30">0:30</span><br/>
<span class="countdown" rel="60">1:00</span><br/>
<span class="countdown" rel="1800">30:00</span><br/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
// Initialization
$(document).ready(function(){
// Replace <span class="countdown"> rel content with the expiry epoch time
var date = new Date(); // This gives you an epoch date in milliseconds
$('span.countdown').each(function(){
// We do rel*1000 to convert to milliseconds, cause rel is in seconds
$(this).attr('rel', date.getTime()+parseInt($(this).attr('rel'))*1000);
});
// Set an interval so updateCountdown() is called every second
setInterval('updateCountdown()', 1000);
});
// Update, called every second
function updateCountdown() {
var date = new Date(); // This gives you an epoch date in milliseconds
// For each <span class="countdown">
$('span.countdown').each(function(){
// Get time left in milliseconds
var timeLeft = parseInt($(this).attr('rel')) - date.getTime();
// Convert from milliseconds to seconds
timeLeft = Math.round(timeLeft/1000);
// Set to 0 if negative
if (timeLeft < 0) timeLeft = 0;
// Extract minutes and seconds for display
var secs = timeLeft % 60;
var mins = (timeLeft-secs)/60;
// Change <span> content
$(this).text(mins+':'+(secs<10?'0':'')+secs);
});
}
</script>

Related

Error date NaN in firefox and IE

Hello I need to spend a given XML through javascript to subtract the current date and time date.
What makes this code is to show the remaining time of a song streaming in minutes and seconds
And then with javascript parsing date and I transform in milliseconds and the current date will also rest in ms.
In Chrome date shows me perfectly, but in Mozilla and IE NaN console shows me and gives error.
I do not understand is that if I have parsed the date because it only works in Chrome. There must be a mistake.
PHP (I draw the start date of a song)
<?php
$xml = # simplexml_load_file('http://www.example.com');
foreach ($xml as $track){
$startTime = $track->starttime;
$songDuration = $track->playduration;
}
?>
JAVASCRIPT:
var spend javascript
var tiempoComienzo= "<?php echo $startTime ?>";
var cancionDuracion="<?php echo $songDuration ?>";
//parse delivered date from php
var d = new Date(Date.parse(tiempoComienzo));
//PHP get the date in milliseconds
var resultPHPms = d.getTime();
//get the current date
var f = new Date();
//step the current date to milliseconds
var resultJSms = f.getTime();
//adding the date of the song to the length of the song
var inicioMasCancion=parseInt(cancionDuracion) + parseInt(resultPHPms);
//It is the challenge to the current date
var TiempoRestante=inicioMasCancion-parseInt(resultJSms);
//pass the result to seconds
seconds=(TiempoRestante/1000)
var container = document.getElementById('time');
var seconds = parseInt(seconds+7);
//step seconds to minutes and seconds
var minutes = parseInt( seconds / 60 ) % 60;
var seconds = seconds % 60;
var contadorDeTiempo=(minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
countdown(seconds);
function countdown:
<script>
var timer;
function countdown(seconds) {
seconds--;
if(seconds >= -1) {
container.innerHTML =contadorDeTiempo;
}
}
timer = setInterval(countdown, 1000);
</script>
HTML:
<span id='time'></span>
In chrome it is perfectly displayed and works perfect. But in Mozilla and IE console NaN it is shown, specifically in this line:
var d = new Date(Date.parse(tiempoComienzo));
How I could solve? The resulting XML date is as follows:
2015-12-20 12:45:33.17
thanks very much for your help

jQuery and PHP Countdown timer from formatted variable

I need to build a countdown timer in jquery that replaces the html in a span tag from a php variable that's formatted to XX Days XX:XX:XX. It should load the variable on page load and then when the jquery script loads it starts the countdown but keeping the same format (XX Days XX:XX:XX) and eventually displays "Expired" and stops the countdown.
I have a jsFiddle started (http://jsfiddle.net/2SDdh/1/) but it shows the formatted time and then loads a 10 sec countdown and eventually shows "Expired". Anyone know how to get the formatting correct?
My HTML output via PHP
<span class="exp">10 Days 10:10:10</span>
My jQuery
$(function(){
var count = 10;
countdown = setInterval(function(){
if (count > 0) {
count--;
$(".exp").html(count);
} else {
$(".exp").html('Expired');
}
}, 1000);
});
try this
html:
<span class="days">10</span> Days <br />
<span class="exp">23:59:59</span>​
javascript :
$(function(){
var days = 10;
var count = 86399;
var count2 = 0;
var hour = 0;
var min = 0;
var sec = 0;
countdown = setInterval(function() {
if (days != 0 || count != 0) {
if (count == 0) {
days--;
count = 86399;
} else {
count--;
}
count2 = count;
hour = Math.floor(count2 / 3600);
count2 = count2 % 3600;
min = Math.floor(count2 / 60);
count2 = count2 % 60;
sec = count2;
$(".exp").html(hour + ":" + min + ":" + sec);
$(".days").html(days);
} else {
$(".exp").html('Expired');
}
}, 1000);
});​
Cheers!
Instead of rolling your own countdown timer, why not use one that already exists?. KK Countdown works well for me.

Javascript .getHours() returns strange result

I'm converting a PHP timestamp into a human readable form in javascript:
<script type="text/javascript">
var timeleft = new Date( <?php echo $lefttime; ?> * 1000 );
var hours = timeleft.getHours();
var minutes = timeleft.getMinutes();
var seconds = timeleft.getSeconds();
var countdown = function() {
console.log( "You have " + hours + ":" + minutes + ":" + seconds + " seconds left" );
</script>
The minutes and seconds work but I'm getting strange results for the hours. For example:
Timestamp: 1976
Function returns: 19:32:56
Any ideas why I'm getting "19" from .getHours() ?
I'm going to hazard a guess that you're in Eastern Time. What you are seeing is $lefttime seconds after the epoch, which in the case of EST is 7PM.
To fix it, just use basic math:
var timeleft = <?php echo $lefttime; ?>;
var hours = Math.floor(timeleft/3600);
var minutes = Math.floor(timeleft/60)%60;
var seconds = timeleft%60;

php countdown server side

i have a question about a javascript/php cron issue. well its not an issue per se but in my case it is.
i have the below javascript that sets a cookie and counts down till the end of that cookie's time. in my case its 10 minutes.
I also have a cron file that runs every 10 minutes.
I would like to synchronize the countdown with the cron file.
The below script works well when i call it from the page however it counts down from the time the user visits the page and its out of sync with the cron file im running.
i understand this is not a php question but the pages im displaying the scripts are php.
Any pointers for me?
Help would be greatly appreciated.
Thank you for reading.
All i have is below.
<div id="countre4">
<script type="text/javascript">
function setCookie(c_name, value)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + 14);
var c_value = escape(value) + "; expires=" + exdate.toUTCString();
document.cookie = c_name + "=" + c_value;
}
function mycountre(countdownId, countdownTarget, countdownSeconds, countdownLooping){
var countre = document.getElementById(countdownId); // get html element
if (!countre) {
return;
}
var target = countdownTarget; // target time
var intervalId; // id of the interval
setCookie("time", target);
// update function
function updatecountre(){
var time = Math.floor((target - new Date().getTime()) / 1000); // countdown time in seconds
if (time < 0) { // if countdown ends
if (countdownLooping) { // if it should loop
target += 1000 * countdownSeconds; // set new target time
time = Math.floor((target - new Date().getTime()) / 1000); // recalculate current time
setCookie("time", target);
} else { // otherwise
clearInterval(intervalId); // clear interval
time = 0; // set time to 0 to avoid displaying negative values
}
}
// split time to seconds, minutes and hours
var seconds = '0' + (time % 60);
time = (time - seconds) / 60;
var minutes = '0' + (time % 60);
time = (time - minutes) / 60;
var hours = '0' + time;
// make string from splited values
var str = hours.substring(hours.length - 2) + ':' + minutes.substring(minutes.length - 2) + ':' + seconds.substring(seconds.length - 2);
countre.innerHTML = str;
}
intervalId = setInterval(updatecountre, 200); // start interval to execute update function periodically
};
var parts = document.cookie.split(';');
var cookie = new Date().getTime() + 1000 * 15 * 60;
for (var i = 0; i < parts.length; ++i) {
if (parts[i].trim().indexOf('time') == 0) {
var value = parts[i].trim().split('=');
cookie = parseInt(value[1]);
}
}
mycountre(
'countre4', // id of the html element
cookie,
10 * 60, // time in seconds (10min here)
true // loop after countdown ends?
);
</script>
</div>
Maybe you should rethink your approach. Don't use a cookie for a piece of information actually stored on the server.
How about instead of a cookie, each PHP page simply set a global JS variable for how much time you have left. Something sorta like this:
<script>
var timeLeft = <? echo $timeLeftInMilliseconds ?>;
startCounter(timeleft);
</script>
Then your counter script can read that and animate a counter accordingly. This leaves it up to your server side code to accurately deliver when the next cron will happen.

Countdown Timer

My project in php
I want to create a countdown timer for asking question in limited timeframe like LMS
here i have use the javascript countdown timer but when refresh the page javascript timer are reset.
You could store the start time in a php session. Then everytime you load a page you can continue the countdown timer with javascript, e.g.
<?php
//on every page
session_start();
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You will need to watch for when the timezones are different, or when the client's clock is wrong. Maybe instead you could calculate the remaining time in seconds and print that into javascript on each page, but then you could have innacuracy over high latency connections etc.
Try something like:
<?php
session_start();
//to reset the saved countdown
if (!empty($_REQUEST['resetCountdown']))
{
unset($_SESSION['startTime']);
}
if (empty($_SESSION['startTime']))
{
$_SESSION['startTime'] = time();
}
//In seconds
$startTime = time() - $_SESSION['startTime'];
?>
<script type="text/javascript">
var countdown = 60; //in seconds
var startTime = <?php echo $startTime; ?>;
startCountdown(startTime, countdown);
function startCountdown(startFrom, duration)
{
//countdown implementation
}
</script>
You could also store the timer in a session variable in PHP so that when the page is refreshed the time is still preserved.
try this
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 1, 2017 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
and also put this under body tag.
<p id="demo"></p>

Categories