timestamp countdown in javascript and php - php

I need some help to code a script that counts down the days, hours, minutes and seconds from a unix timestamp.
timestamp is created with php
<? php echo hours ();?>
And I want the script to count down in real time with JavaScript.
Example
2 days, 3:15:39
Hope someone can help me a little:)

First you have some PHP errors. It should be e.g.
<?php echo time(); ?>
I'm using a timestamp in JavaScript for the ease of showing an example.
http://jsfiddle.net/pimvdb/AvXd3/
// the difference timestamp
var timestamp = (Date.now() + 1000 * 60 * 60 * 24 * 3) - Date.now();
timestamp /= 1000; // from ms to seconds
function component(x, v) {
return Math.floor(x / v);
}
var $div = $('div');
setInterval(function() { // execute code each second
timestamp--; // decrement timestamp with one second each second
var days = component(timestamp, 24 * 60 * 60), // calculate days from timestamp
hours = component(timestamp, 60 * 60) % 24, // hours
minutes = component(timestamp, 60) % 60, // minutes
seconds = component(timestamp, 1) % 60; // seconds
$div.html(days + " days, " + hours + ":" + minutes + ":" + seconds); // display
}, 1000); // interval each second = 1000 ms

Related

Whatsapp sharing button with a countdown variable

Beginner in web coding, I have issue to code a sharing button that lead to whatsapp and that share a countdown.
I achieve it with static string but I can't load a variable in it...
Does someone know where my issue is please ?
<script>
// Set the date we're counting down to
var countDownDate = new Date("Aug 20, 2022 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and 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);
var countdown_iam = days + "j " + hours + "h "
+ minutes + "m " + seconds + "s "
// Output the result in an element with id="countdown"
document.getElementById("countdown").innerHTML = countdown_iam;
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "SURPRISE!!!";
}
}, 1000);
function openWhatsApp() {
//var countdown_whatsapp = "test";
//alert(countdown_iam);
window.open('whatsapp://send?text=' + countdown_iam);
}
</script>
<h2> WhatsApp sharing Link </h2>
<!-- create an image icon to open the WhatsApp onclick -->
<img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()">
Thank's for your help
The countdown_iam variable is created within a function and only exists within that function. So when the other function (openWhatsApp) tries to use the variable, it can't find it and the error occurs.
You want to access the countdown string from two different functions, so one option would be to create a new function that makes the countdown string and returns it. You can then call that function from both places. I've done that here:
<script>
function getCountdown() {
var countdownDate = new Date("Aug 20, 2022 12:00:00").getTime();
var now = new Date().getTime();
var distance = (countdownDate - now) / 1000;
if (distance < 0) {
return 'SURPRISE!!!';
} else {
var days = Math.floor(distance / (60 * 60 * 24));
var hours = Math.floor((distance % (60 * 60 * 24)) / (60 * 60));
var minutes = Math.floor((distance % (60 * 60)) / 60);
var seconds = Math.floor(distance % 60);
return days + "j " + hours + "h " + minutes + "m " + seconds + "s ";
}
}
function openWhatsApp() {
alert('whatsapp://send?text=' + getCountdown());
}
setInterval(function() {
document.getElementById("countdown").innerHTML = getCountdown();
}, 1000);
</script>
<h2>WhatsApp Sharing Link</h2>
<p id="countdown"></p>
<p><img src="img/whatsapp.png" height="50" size="50" onclick="openWhatsApp()"></p>

PHP Countdown from Day Hour Minute Second

Want to show a countdown of Days Left, Hour, Minute, Second.
The time data comes in this format:
startTime: "2017-02-17T13:51:13",
I found a example script found on stack:
<?php
$now = new DateTime();
$ends = new DateTime('May 31, 2017, 11:59 pm');
$left = $now->diff($ends);
?>
<dd>
<div class="timer_wrp">Remaining
<ul class="timer countdown">
<li><i><?php echo $left->format('%a'); ?></i>Day</li>
<li><i><?php echo $left->format('%h'); ?></i>Hour</li>
<li><i><?php echo $left->format('%i'); ?></i>Min</li>
<li><i><?php echo $left->format('%s'); ?></i>Sec</li>
</ul>
</div>
The Date format is different, is there a easy way to use how its currently setup or would I have to change that into the example format? And do you see anything that maybe missing from this example? Thanks
check this. If you don't set the time zone your calculation may be wrong. Because, by default it takes the server time zone. It might have other solution but in my case, I always use javascript.
<?php
date_default_timezone_set("Asia/Calcutta");
$now = new DateTime();
$ends = new DateTime('Oct 9, 2020, 4:40:00');
$left = $now->diff($ends);
?>
<div class="timer">
<p>Remaining </p>
<ul class="timer countdown">
<li><i><?php echo $left->format('%a'); ?></i>Day</li>
<li><i><?php echo $left->format('%h'); ?></i>Hour</li>
<li><i><?php echo $left->format('%i'); ?></i>Min</li>
<li><i><?php echo $left->format('%s'); ?></i>Sec</li>
</ul>
</div>
You may need this one also. This one is written in javascript. Copy both and see the difference.
<p id="demo"></p>
<!--javascript-->
<script>
// Set the date we're counting down to
var countDownDate = new Date("Oct 9, 2020 4:40:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and 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>

How to find at what time activity finished?

I have activity start time and and total hour i just want to find the end time of that activity i mean time when activity finished ?
for example I start my activity
for
$hour = 24:60:08 // 24 hour 60 min 8 min total hour
$starttime = 13:09 // using 24 hour format it 01:09
//means activity start at = 13:09
$endtime = ?
I want to find out the the time finished time of an activity
Thanks
You can with adding to time exploded hour like following:
$hour = '24:60:08';
$starttime = '13:09';
$times = explode(':', $hour);
$timestamp = strtotime($starttime) + ($times[0] * 3600 + $times[1] * 60 + $times[2]);
$endtime = date('H:i', $timestamp);
echo $endtime; // 14:09
Explain:
24 = 24(hours) * 60(mins) * 60(secs)
60 = 60(mins) * 60(secs)
08 = 8(sec)
It appears like you have a start time of an activity and then a duration of how long it ran and you want to compute what's the end time. Your question becomes unclear by your use of non descriptive variable names nor any comments. You can do
<?php
$duration = "25:00:08";
$starttime = "13:09";
list($hours,$minutes,$seconds) = explode(":",$duration);
$totalTime = $seconds+($minutes*60)+($hours*3600);
$endTime = date("h:i",strtotime($starttime)+$totalTime);
echo $endTime;
?>
Sidenote: 24:60:08, 60 minutes is nothing. That's 25 hours 0 minutes and 8 seconds
If you want to get the time elapsed to process something, let's say to execute a function, you can easily do it with PHP microtime.
Assume you want to find time elapsed to execute function test, here how you do this.
public function test()
{
$time_start = microtime(true);
/*
Your code
goes here
*/
$time_end = microtime(true);
$execution_time = (($time_end - $time_start) / 60) * 60;
echo $execution_time; //This will show you the execution time in seconds.
}
If you want, you can add this seconds to any previous time stamp you saved, in order to get the execution terminated time in hh:mm:ss format. Hope this helps.
Cheers!
I am unable to understand exactly what you are looking for
<?php
$hour = "24:60:08"; // 24 hour 60 min 8 min total hour
$starttime = "13:09";
$hourArray=explode(":", $hour);
$starttimeArray=explode(":", $starttime);
$endtimearray=array();
for ($i=0;$i<3;$i++){
//Verifyng time is set else making it zero
if (!isset($hourArray[$i]))
$hourArray[$i]=0;
if (!isset($starttimeArray[$i]))
$starttimeArray[$i]=0;
$endtimearray[$i]=$hourArray[$i]-$starttimeArray[$i];
}
echo $endtimearray[0];
for ($i=1;$i<3;$i++)
echo ":$endtimearray[$i]";
Hopefully This is what you are looking for.

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";
?>

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