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";
?>
Related
I'm building a check in and out system for my work, the employee can set a start time and after his shift he can set the end time. but here is the problem:
If i start at 17:00 till 23:15 I want to show te result as 6.25 hours worked.
For example 15 minutes (¼ hour) equals .25, 30 minutes (½ hour) equals .50, etc.
Googled a lot of this but i can't find a solution for php.
Someone who can help me with this? :)
Many thanks.
There isn't one function, but the DateTimeInterface (http://php.net/manual/en/class.datetimeinterface.php) provides some tools to help, along with some basic maths:
<?php
const secsInAnHour = 3600;
const minsInAnHour = 60;
const hoursInADay = 24;
const decimalPlaces = 2;
$date1 = new DateTime();
$date2 = new DateTime();
$date1->setTime(17, 00);
$date2->setTime(23, 15);
$diff = $date2->diff($date1);
$convertToHours = $diff->s / secsInAnHour + $diff->i / minsInAnHour + $diff->h + $diff->days * hoursInADay;
$hours = round($convertToHours, decimalPlaces);
// Hours between two dateTimes, to 2 dp.
echo $hours;
You could put this into a function inside your implementation, if you wanted to (with start and end times as args).
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>
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
I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
** Note ** It will always be less than 24 hours difference.
Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
$start = strtotime($now);
As an alternative you could get the timestamp like this according to the documentation
$start = $now->getTime();
To do it without pear, to find the seconds 'till 17:00 you can do:
$current_time = mktime ();
$target_time = strtotime (date ('Y-m-d'. ' 17:00:00'));
$timediff = $target_time - $current_time;
Not tested it, but it should do what you need.
I don't think you should be passing the entire Date object to strtotime. Use one of these instead;
$start = strtotime($now->getDate());
or
$start = $now->getTime();
Maybe some folks wanna have the time difference the facebook way. It tells you "one minute ago", or "2 days ago", etc... Here is my code:
function getTimeDifferenceToNowString($timeToCompare) {
// get current time
$currentTime = new Date();
$currentTimeInSeconds = strtotime($currentTime);
$timeToCompareInSeconds = strtotime($timeToCompare);
// get delta between $time and $currentTime
$delta = $currentTimeInSeconds - $timeToCompareInSeconds;
// if delta is more than 7 days print the date
if ($delta > 60 * 60 * 24 *7 ) {
return $timeToCompare;
}
// if delta is more than 24 hours print in days
else if ($delta > 60 * 60 *24) {
$days = $delta / (60*60 *24);
return $days . " days ago";
}
// if delta is more than 60 minutes, print in hours
else if ($delta > 60 * 60){
$hours = $delta / (60*60);
return $hours . " hours ago";
}
// if delta is more than 60 seconds print in minutes
else if ($delta > 60) {
$minutes = $delta / 60;
return $minutes . " minutes ago";
}
// actually for now: if it is less or equal to 60 seconds, just say it is a minute
return "one minute ago";
}
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>