I'm looking to create a dynamic javascript countdown timer, I want to pass it a datetime variable from my SQL server database and have it count down to this date then display a message, I've tried nearly every JQuery plugin I can find and Havent been able to edit them to do what I need, I also need to be able to have multiple countdown timers on the same page,
Any help would be much appriciated
Cheers
Scott
=======EDIT=======
After much Trial and Error I was able to modify this js http://andrewu.co.uk/clj/countdown/pro/
to do what I needed
try this:
function Thick(startin) {
startin--;
document.getElementById('timer').innerHTML = startin;
if(startin > 0) setTimeout('Thick(' + startin + ')', 1000);
}
call thus function in body onLoad like:
<body onLoad="Thick(20);">
hope this help :)
//TODAY'S DATE
$today = time();
//FETCHES DATE AND TIME FOR THE EVENT FROM DATABASE
$sql = "SELECT * FROM post";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$Row = (mysqli_fetch_assoc($result));
$th = $Row['endtime'];
}
echo $th
first of all put it into a variable then use your javascript to call the variable
//let get todays date here
var today = new Date();
var DD = today.getDate();
var MM = today.getMonth()+1; //January is 0!
var YYYY = today.getFullYear();
//let get the Difference in Sec btw the two dates
var _DateFromDBProgEndDate = '<?php echo $th; ?>';
var ProgEndTime = new Date(_DateFromDBProgEndDate);
var TodayTime = new Date();
var differenceTravel = ProgEndTime.getTime()- TodayTime.getTime() ;
var seconds = Math.floor((differenceTravel) / (1000));
////////////////////////////////
var SecDiffFromToday = seconds;
var seconds = SecDiffFromToday;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
the javascript call in the variable with '<?php echo $th; ?>'; then the javascript does the count down with out refreshing the page
Related
I want to show current time on my webpage. When I push F5, I can get the time, but it's not changing. Help me..
HTML
<div id="time" class="timer">
show_time
</div>
Javascript
var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
dn="AM";
if (hours>12)
hours=hours-12;
if (hours==0)
hours=12;
if (minutes<=9)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;
setInterval(setTime, 1000);
function setTime(){
text2.innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
setTime();
Thank you!
Try this
const el = document.getElementById('nav-time');
function updateClock() {
var now = new Date();
var time = now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
el.innerHTML = time;
}
setInterval(updateClock, 1);
<li><span id="nav-time">Clock
<span class="divider"> | </span>
function setTime(){
document.getElementById("time").innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
You have to add something to your current code so that your setTime function actually adds its output to the DOM. I used document.getElementById("time") to add the time from your function to the page.
You need to get the current time inside the function, otherwise it will return value that you got when function was called for the firs time
function setTime(){
var text2 = document.getElementById("time");
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds();
var dn = "PM";
if (hours<12)
dn="AM";
if (hours>12)
hours=hours-12;
if (hours==0)
hours=12;
if (minutes<=9)
minutes="0"+minutes;
if (seconds<=9)
seconds="0"+seconds;
text2.innerHTML ="현재 시간: <br>"+ hours + ':' +
minutes + ':' + seconds+ "<bn>"+dn;
}
setTime();
setInterval(setTime, 1000);
https://jsfiddle.net/1gc8ymkd/
I am trying to show a live javascript clock on my page which shows the time on the server. I found this snippet of code on the internet a few weeks back however it doesn't seem to be doing what it claimed to do. It is showing the client time, not the server time. Any idea why?
flag = true;
timer = '';
setInterval(function(){phpJavascriptClock(<?php echo time(); ?>);},1000);
function phpJavascriptClock(timestamp)
{
if ( flag ) {
timer = timestamp * 1000;
}
var d = new Date(timer);
var currentDate = d.getDate();
currentDate = currentDate < 10 ? '0'+currentDate : currentDate;
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ' ' + ampm;
var output = '';
output +=
'<a>'
+ '<i class="ace-icon fa fa-clock-o"></i>'
+ '<span class="">' + strTime + ' (SA)</span>'
+ '</a>'
;
document.getElementById("current_time").innerHTML = output ;
flag = false;
timer = timer + 1000;
}
I see these 4 constructors for a Javascript DATE:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Could it be your timestamp is not milliseconds or dateString so Javascript just creates a new Date() object without any parameters (which is then the client time)?
Wrote a new jQuery based clock. Although it polls the server every minute, it works.
My controller that passes the time:
public function getServerTimeAction() {
global $config;
try{
$return["time"] = date("H:i a");
$return["timezone"] = $config->application->timezone;
$this->returnJson( JsonReturnObject::success( $return ) ) ;
} catch ( Exception $e ) {
$this->returnJson( JsonReturnObject::error( $e ) );
}
}
The jquery code:
function getServerTime() {
$.ajax({
url : "{{ url('json/session/get-server-time') }}",
cache : false,
success : function ( data ) {
if ( data.success ) {
var output = '';
output +=
'<a>'
+ '<i class="ace-icon fa fa-clock-o"></i>'
+ '<span class="">' + data.data.time + ' (SA)</span>'
+ '</a>'
;
$("#current_time").html(output);
setTimeout(getServerTime, 60000);
}
}
})
}
Well, I'm making a game, and in my game I have a countdown script in javascript that receives the date when the building upgrade is over, and makes a countdown, and when the countdown ends, executes a script that upgrades the building to the next level.
But just works in google chrome, and in the other browsers appears like that:
Firefox:
Google Chrome
Just the Javascript:
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
Complete function:
function factory_update($get){
$userid = $_SESSION['userid'];
$query00 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result00 = mysql_query($query00) or die(mysql_error());
while($row00 = mysql_fetch_array($result00)){
$factory_upgrade = $row00['userid'];
}
if(!isset($factory_upgrade)){
echo "Sem melhoramentos.";
return 0;
}
$query01 = "SELECT * FROM factory_upgrading WHERE userid = '$userid'";
$result01 = mysql_query($query01) or die(mysql_error());
while($row01 = mysql_fetch_array($result01)){
$factory_level = $row01['new_level'];
$factory_date = $row01['upgraded'];
}
if ($get == "load")
{
echo '<div class="message_upgrades" ">';
echo '<div class="loading"><img src="/images/loading.gif"></img></div>';
echo '</div>';}
else
{
date_default_timezone_set('europe/lisbon');
$datephp = date('Y-m-d H:i:s');
echo'
<script type="text/javascript">
function cdtd() {
var xmas = new Date("' . $factory_date . '");
var now = new Date();
var timeDiff = xmas.getTime() - now.getTime();
if (timeDiff <= 0) {
clearTimeout(timer);
$("#factory_upgrade").load("/include/factory_upgraded.php");
$("#quantidade_fabricas").load("/include/factory_stats.php");
}
var seconds = Math.floor(timeDiff / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;' .
"var tempo=('0' + hours).slice(-2)+':'+('0' + minutes).slice(-2)+':'+('0' + seconds).slice(-2);"
.
'
document.getElementById("secsBox").innerHTML = tempo;
var timer = setTimeout("cdtd()",1000);
}
</script>
';
echo '<div class="success_upgrades">';
echo '<div class="upgrade_text"><b>Nivel: </b>' . $factory_level . '</div><div class="div_separator"></div><div class="upgrade_text"><b>Duração:</b>
<div class="secsBox" id="secsBox"></div>
<script type="text/javascript">cdtd();</script></div><div class="div_separator"></div>
';
echo '<div id="close" class="stop_upgrade" ></img></div>';
echo '</div>';
echo '<script>
$(".stop_upgrade").click(function (e) {
e.preventDefault();
$(factory_upgrade2).empty();
setTimeout(function(){
$("#factory_upgrade2").load("/include/upgrade_cancel.php");
$("#factory_upgrade").load("/include/factory_update.php");
$("#load").load("/include/cabecalho_content.php");
$("#industrial").fadeIn();
$(loader1).delay(1000).hide(0);
}, 100);
});
</script>
';
}
}
The format of $factory_date is invalid according to standard JavaScript and Chrome happens to be able to parse it.
For better results, stick to these Date constructors:
new Date();
new Date(value);
new Date(dateString);
new Date(year, month [, day, hour, minute, second, millisecond]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
I have this code for a countdown timer. its basically a combination of PHP/Javascript countdown timer which will gets the $end_date from a Mysql table/field.
The problem is that it will stop automatically (which is unwanted) at a certain time.
For example: I set the $end_date to September 19 2013 11:30:00 AM GMT in mysql database.
the countdown starts and works fine and starts counting down as it should. However, when the countdown timer reaches September 19 2013 13:00:00 PM GMT it will stop and it will show the Times Up message! Basically it will stop working or counting down once the $end_date has been changed to 13:00:00 PM.
I cannot see anything in my code that will cause this issue. apart from this line:
if ($now < $exp_date ) {
?>
but again, this line only tells the script when to start counting and as far i can see it shouldn't stop the countdown timer to stop as long as the timer has not reached the $end_date. or am I missing something?
here is my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
?>
<?php date_default_timezone_set('GMT'); ?>
<?php
session_start();
// Run a select query to get my letest 6 items
// Connect to the MySQL database
include "config/connect.php";
$dynamicList = "";
$sql = "SELECT * FROM item ORDER BY id";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$id = $row["id"];
$product_name = $row["product_name"];
$date_added = date("Y-m-d", strtotime($row["date_added"]));
$end_date = date("F d Y H:i:s A T", strtotime($row["end_date"]));
$price = $row["price"];
$dynamicList .= '<div>' . $end_date . '
</div>';
}
} else {
$dynamicList = "No Records";
}
?>
<?php
$date = $end_date;
$exp_date = strtotime($date);
$now = time();
if ($now < $exp_date ) {
?>
<script>
// Count down milliseconds = server_end - server_now = client_end - client_now
var server_end = <?php echo $exp_date; ?> * 1000;
var server_now = <?php echo time(); ?> * 1000;
var client_now = new Date().getTime();
var end = server_end - server_now + client_now; // this is the real end time
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour *24
var timer;
function showRemaining()
{
var now = new Date();
var distance = end - now;
if (distance < 0 ) {
clearInterval( timer );
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor( (distance % _day ) / _hour );
var minutes = Math.floor( (distance % _hour) / _minute );
var seconds = Math.floor( (distance % _minute) / _second );
var countdown = document.getElementById('countdown');
countdown.innerHTML = '';
if (days) {
countdown.innerHTML += 'Days: ' + days + '<br />';
}
countdown.innerHTML += 'Hours: ' + hours+ '<br />';
countdown.innerHTML += 'Minutes: ' + minutes+ '<br />';
countdown.innerHTML += 'Seconds: ' + seconds+ '<br />';
}
timer = setInterval(showRemaining, 1000);
</script>
<?php
} else {
echo "Times Up";
}
?>
<div id="countdown"></div>
any help would be greatly appreciated.
13:00:00 PM is not a valid time. AM and PM are used to indicate which side of the 12-hour cycle the time is. You cannot logically say you're on the 13th hour of the 12 hour side of the clock.
EDIT: For clarity: 13:00 == 1 PM, 13:00 PM == nothing.
I have the following javascript that prints the timestamp:
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(hours + "" + minutes + seconds + month + "" + day + "" + year)
//-->
</script>
However I want to use this timestamp in many places in the page, how can i call it like $timestamp so i can control where its placed?
Thanks in advance.
Set a variable, like:
var timestamp = hours + "" + minutes + seconds + month + "" + day + "" + year;
and later in code use that variable to show info in your page, like:
var container = document.getElementById('container1');
container.innerHTML = timestamp;
where 'container1' is a html element like span, div, p, etc. ex:
<span id="container1"></span>
answer
<script>
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<span id="txt"></span>
<script type="text/javascript">
startTime().swap('txt');
</script>