PHP/Javascript countdown script - php

Note * I want some one to fix it and tell me how they did it not tips on how to do it or coments about php nd java mixed in it *
I have a countdown script that is working, but when it hits the target date the timer keeps on going to a negative time. I want it to stop on that target date and just display a finishing message. It's live on my site. I just need help editing the countdown script.
I want to keep the same layout. I need some help adding the finishing message and stopping it from going into the negative date, or just make it not display the 0days, 0 hours, 0mins, 0sec until the site's officially released. When that finally happens, I want it to display a message.
countdown script
<?php date_default_timezone_set('EST'); ?>
<?php
// Define your target date here
$targetYear = 2011;
$targetMonth = 9;
$targetDay = 1;
$targetHour = 20;
$targetMinute= 00;
$targetSecond= 00;
// End target date definition
// Define date format
$dateFormat = "Y-m-d H:i:s";
$targetDate = mktime($targetHour,$targetMinute,$targetSecond,$targetMonth,$targetDay,$targetYear);
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$targetDateDisplay = date($dateFormat,$targetDate);
$actualDateDisplay = date($dateFormat,$actualDate);
?>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
</script>
<body onLoad="setCountDown();">
<center><?php echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";?> untill official release</center>
how its added on the site
<script type="text/javascript">
$(function() {
/* Union War */
$("#Countdown2").load("http://imperialism.zxq.net/includes/process/uwcountdown.php");
setInterval(function(){
$("#Countdown2").load("http://imperialism.zxq.net/includes/process/uwcountdown.php");
}, 1000);
});
</script>
<div id="uwCD" class="uwCD">
<div id="Countdown2"></div>
</div>

I recommend this jQuery countdown plugin; just pass the PHP value to the jQuery plugin call.

if($targetDate != $actualDate && $targetDate > $actualDate) {
echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";
} else {
echo "0 days, 0 hours, 0 minutes and 0 seconds";
}

try using this http://www.timeanddate.com/counters/customcount.html everything is done for you and its worked fine and if anything you can just edit the look of the skin to fit your website

if($targetDate != $actualDate && $targetDate > $actualDate) {
echo "$remainingDay days, $remainingHour hours, $remainingMinutes minutes and $remainingSeconds seconds";
} else {
echo "0 days, 0 hours, 0 minutes and 0 seconds";
}

Related

How to make a countup timer instead of a countdown timer? (PHP, JQUERY AJAX)

I made a countdowntimer in PHP and jQuery AJAX who is showing every second the variable named $timeleft.
timer.js
$(function()
{
var timertext = $("[timer]");
setInterval(function()
{
$.post("timer.php", {type : "timerupdate"}, function(data)
{
timertext.html("Time left: " + data + " seconds")
});
}, 1000);
});
timer.php
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
if(date('Y-m-d H:i:s') >= $startdatetime){
$timeleft = $timecountdownend - $timecountdownstart;
if(isset($_POST["type"]) === true && $_POST["type"] == "timerupdate")
{
echo ($timeleft);
}
}
Explained: a timer that starts when it's a specific time ($startdatetime) and counting the seconds till the $timecountdownend time. It's working fine, but I actually want to count up the second instead of counting down. So that it start counting with 1 second if $startdatetime has reached and every second is counting up till the $timecountdownend has reached. How can I do this with strtotime? I've tried many things like $timeleft = $timecountdownend - strtotime(date('Y-m-d H:i:s')); but it didn't work.
Many thanks in advance.
First if You have timeleft its Your counter : -2820
You can simply multiple it by (-1) : -2820 * (-1) = 2820
date_default_timezone_set("Europe/Amsterdam");
$timecountdownend = strtotime("2020-05-18 14:30:00");
$timecountdownstart = strtotime("now");
$startdatetime = "2020-05-18 14:07:00"; //variable for starting datetime
$timeleft = $timecountdownend - $timecountdownstart;
echo ($timeleft);
echo(PHP_EOL);
echo ($timeleft*(-1));
echo(PHP_EOL);
echo( date('Y-m-d h:i:sa',strtotime($startdatetime)+$timeleft*(-1)));
http://sandbox.onlinephpfunctions.com/code/792ec42255d85a45c377b6e8d34cbde143430824

Hide PHP Countdown Timer When Timer Reaches 0

I have this PHP countdown timer script, and I'm trying to have JQuery hide the timer when it reaches 0 days, 0 hours, 0 mins, 0 secs. I know the JQuery show() and hide() functions can be used here, however I am unaware of how to trigger those JQuery functions when the PHP countdown timer reaches 0.
PHP code:
$secs = strtotime("2013-06-23 17:00:00 +1 GMT") - time();
$days = floor($secs / 86400);
$secs %= 86400;
$hours = floor($secs / 3600);
$secs %= 3600;
$mins = floor($secs / 60);
$secs %= 60;
echo "<div class='value'>$days<br><p class='time'>Days</p></div>";
echo "<div class='value'>$hours<br><p class='time'>Hours</p></div>";
echo "<div class='value'>$mins<br><p class='time'>Mins</p></div>";
echo "<div class='value'>$secs<br><p class='time'>Secs</p></div>";
?>
JQuery I'm using:
$(document).ready(function(){
setInterval(function(){
$("#timer").load("date.php");
});
});
The countdown timer is displayed in this div:
<div id="timer"></div>
I've rewritten your code using JSON instead. Here it is:
HTML:
<div class="countdown">
<div class="days"><span>$days</span><br> <p>Days</p></div>";
<div class="hours"><span>$hours</span><br> <p>Hours</p></div>";
<div class="minutes"><span>$mins</span><br> <p>Mins</p></div>";
<div class="seconds"><span>$secs</span><br> <p>Secs</p></div>";
</div>
JS:
$.getJSON("date.php").done(function(data){
if(data.zero){
// timer is 0 so hide
$('.countdown').fadeOut();
}else{
$('.countdown').fadeOut(function(){
$(this).find('.days span').html(data.days);
$(this).find('.hours span').html(data.hours);
$(this).find('.minutes span').html(data.minutes);
$(this).find('.seconds span').html(data.seconds);
$(this).fadeIn();
});
}
}).fail(function(){
// if it fails this function will be called
});
PHP:
<?php
$json = array();
$json['seconds'] = strtotime("2013-06-23 17:00:00 +1 GMT") - time();
$json['days'] = floor($secs / 86400);
$json['seconds'] %= 86400;
$json['hours'] = floor($secs / 3600);
$json['seconds'] %= 3600;
$json['minutes'] = floor($secs / 60);
$json['seconds'] %= 60;
$json['zero'] = array_sum($json) > 0 ? false : true;
echo json_encode($json)
?>
As mentioned, you can use Javascript for this entirely.
If you do wish to use PHP + Javascript, you need to expand your timer callback to parse the time. Check this question for an example:
javascript: how to parse a date string
Once you parse the various parts of the time, you can then use hide() if the timer reaches zero.
With jQuery, you can parse the time parts like this:
var days = $("#timer .value").eq(0).html();
var hours = $("#timer .value").eq(1).html();
var mins = $("#timer .value").eq(2).html();
var secs = $("#timer .value").eq(3).html();
However, you will need to put the value itself in a separate div, i.e. something like:
echo "<div class='value'>$days</div><div><br><p class='time'>Days</p></div>";
echo "<div class='value'>$hours</div><div><br><p class='time'>Hours</p></div>";
echo "<div class='value'>$mins</div><div><br><p class='time'>Mins</p></div>";
echo "<div class='value'>$secs</div><div><br><p class='time'>Secs</p></div>";
This way, you can get the whole contents of the value div without breaking up the value it contains into chunks. If you absolutely must have everything in the same div, you can split the div contents with Javascript's split() function:
http://www.w3schools.com/jsref/jsref_split.asp
You could just hide it with jQuery... Something like this:
$(document).ready(function(){
if ($("#timer:contains('0 days, 0 hours, 0 mins, 0 secs')").length) {
$("#timer").hide();
}
});
Demo

how to make countdown timer to not reset on page refresh

I am creating an online exam page for my project. I have a countdown timer, but it resets on page refresh. How can I make it not to reset?
The timer is set by fetching time from db. I am using php mysql. Please help me.
Here is my code.
<?php
$result=mysql_query("select * from test where testid='29'");
while($time=mysql_fetch_array($result)){
$dateFormat = "d F Y -- g:i a";
$targetDate = time() + ($time['duration']*60);
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown ()
{
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
hours = 23
}
document.getElementById("remain").innerHTML = " "+hours+" hr "+minutes+" min "+seconds+" sec";
SD=window.setTimeout( "setCountDown()", 1000 );
if (minutes == '00' && seconds == '00') {
seconds = "00"; window.clearTimeout(SD);
window.location = "result.php"
}
}
</script>
</head>
<body onLoad="setCountDown();">
<div id="remain">
<?php echo "$remainingHour hours, $remainingMinutes minutes, $remainingSeconds seconds";?>
</div>
You should read the value into session variable and using that afterwards:
<?php
session_start();
if (isset($_SESSION['targetdate'])) {
// session variable_exists, use that
$targetDate = $_SESSION['targetdate'];
} else {
// No session variable, red from mysql
$result=mysql_query("select * from test where testid='29' LIMIT 1");
$time=mysql_fetch_array($result);
$dateFormat = "d F Y -- g:i a";
$targetDate = time() + ($time['duration']*60);
$_SESSION['targetdate'] = $targetDate;
}
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)- ($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)- ($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
?>
When the user starts the exam, save the start time in the database. Use that for everything. Don't rely on client side code for this as the user can easily modify it.
If you save the start time, you know when the user started and what the current time is. You can use that to see if time is up or not. A javascript timer is good to show how much time is remaining, but it should be getting that info from the database.
You'll probably need to register a table like active_exams with an examId field and datetimeStarted. Then load the timer as the number of seconds for that exam since it was started.
You may be able to create some workaround with cookies, localStorage or even the session but keep in mind those will be modifiable (or at least forgettable in the case of the session) by the user.
Page refresh doesn't matter if you have the Timer's "start-time" saved in your database for particular user.
Fetch this "start-time" from database and compute it to get the consumed time and accordingly show the remaining or elapsed time.

Trying to use jQuery Countdown with UNIX timestamp from php

As the title says I'm facing a problem displaying the right left time to an end date.
I'm using this jquery plugin: http://keith-wood.name/countdown.html
Let's assume that our timestamp is generated by a PHP script like this: $end_date = strtotime($row4['end']); // 2012-05-09 06:00:00 becomes 1336536000
I use this ($i is used inside a loop):
$('.count-<?php echo $i; ?>').countdown({until: new Date(<?php echo $end_date; ?> * 1000), layout: '{dn} days {hnn} hrs {mnn} min {snn} sec', compact: true});
Right now it's 06:21 AM here. Instead of the expected 1 day left result I get "1 days 17 hrs 04 min 21 sec".
What am I missing here?
I have been using the API for quite a while now, but I cann't seem to figure out what's up with your code. Perhaps (but just perhaps) you're using the untill property wrong.
My code that I usually use:
$(function(){
var countdown = $('#countdown'),
ts = new Date(<?php echo $date_to * 1000; ?>),
finished = true;
if((new Date()) > ts)
{
finished = false;
}
$('#cool-countdown').countdown({
timestamp : ts,
callback : function(days, hours, minutes, seconds)
{
var message = "";
message += days + " days, ";
message += hours + " hours, ";
message += minutes + " minutes, ";
message += seconds + " seconds ";
message = (finished ? "Countdown finished" : "left untill the New Year");
countdown.html(message);
}
});
});
Obviously you should extend this to feature singular.

How to make a countdown using PHP

Im creating a website for my brothers wedding. And so far all is going well. However, he wants a countdown to the wedding on the homepage;
Time left until the wedding: X months, X days, X hours.
I would preferebly like to do this using php, but would be open to other suggestions.
if you can help me with ideas for the coding, or just point me to relevant material, that would be useful.
The wedding is on Saturday 30th July.
If your need your counter to be displayed only on page refresh and be static once the page is loaded, then PHP will be fine.
If you need the countdown to get refreshed when the page is displayed, you'll need to use JavaScript.
Personally I would go for something already implemented, like that small script.
Following is the code snippet I have copied from the W3Schools website, while added my PHP code to get the "countdown to" timestamp and the "now" timestamp.
You will see I have commented out the original JavaScript code and replaced it with PHP code in two places, so it's clear to tell what's the difference between two options.
Basically when you think the "server time" is more reliable in your case, you can adopt the PHP approach.
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
// 1. JavaScript
// var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
// 2. PHP
var countDownDate = <?php echo strtotime('Sep 5, 2018 15:37:25') ?> * 1000;
var now = <?php echo time() ?> * 1000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
// 1. JavaScript
// var now = new Date().getTime();
// 2. PHP
now = now + 1000;
// 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>
</body>
</html>
For Static Countdown :
<?php
//A: RECORDS TODAY'S Date And Time
$today = time();
//B: RECORDS Date And Time OF YOUR EVENT
$event = mktime(0,0,0,12,25,2006);
//C: COMPUTES THE DAYS UNTIL THE EVENT.
$countdown = round(($event - $today)/86400);
//D: DISPLAYS COUNTDOWN UNTIL EVENT
echo "$countdown days until Christmas";
?>
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
Code top by user Neil E. Pearson didnĀ“t work, he forgot to write there the brackets (), working solution is:
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / (60*60*24)); // here the brackets
$hours = floor(($secondsLeft - ($days*60*60*24)) / (60*60)); // and here too
echo "$days days and $hours hours left";
$Target_Date = 1699458858; //expire data
$Time_Left = $Target_Date - time();
$days = floor($Time_Left / (60*60*24));//day
$Time_Left %= (60 * 60 * 24);
$hours = floor($Time_Left / (60 * 60));//hour
$Time_Left %= (60 * 60);
$min = floor($Time_Left / 60);//min
$Time_Left %= 60;
$sec = $Time_Left;//sec
echo "$days days and $hours hours and $min min and $sec sec left";
I would not use php (serverside) for this. Because you need to refresh your page every time to see the counting. Preferably use javascript (clientside) for this, more specific jquery (javascript framework). And look for a jquery plugin such as: http://keith-wood.name/countdown.html
If you want something realtime, you'll need to use client-side scripting, namely JavaScript.
You can do it in PHP, but it won't "animate":
$wedding = strtotime("2011-07-01 12:00:00+0400"); // or whenever the wedding is
$secondsLeft = $wedding - time();
$days = floor($secondsLeft / 60*60*24);
$hours = floor(($secondsLeft - $days*60*60*24) / 60*60);
echo "$days days and $hours hours left";
You could put some more math in for months, but it gets fuzzier because a month isn't a fixed amount of time.
The other way would be to use the date() function to pick out the individual elements (hour, minute, second, day, month etc) and use rollover math, but it's a lot of bother for a 'nice effect'.
Let me know if you want a JavaScript example. Don't bother with jQuery - it's a canon for killing a mosquito :)
try this
<?php
$target = mktime(0, 0, 0, 9, 25, 2011) ;//set marriage date
$today = time () ;
$difference =($target-$today) ;
$month =date('m',$difference) ;
$days =date('d',$difference) ;
$hours =date('h',$difference) ;
print $month." month".$days." days".$hours."hours left";
?>
Try this
$wedding = strtotime("2014-02-20 12:00:00"); // or whenever the wedding is
$current=strtotime('now');
$diffference =$wedding-$current;
$days=floor($diffference / (60*60*24));
echo "$days days left";
Try this static countdown.
<?php
//Current Date And Time
$todaytime = time();
//Set Date And Time OF The Event
$eventdate = mktime(0,0,0,0,28,2021);
//Calculate Days Until The Event
$countdown = round(($eventdate - $todaytime)/86400);
//Display Countdown
echo "$countdown days until the event";
?>

Categories