jQuery Time ago from a timestamp? - php

Below is a really nice time ago plugin for jQuery, very similar to what they use here on SO. The problem for me is that it uses this to convert time.
<time class="timeago" datetime="2008-07-17T09:24:17Z">July 17, 2008</time>
That would be great except that I store time on my site in UTC timestamp and not as a formatted time, is there a way to convert something like this to use a timestamp? I know in PHP I could convert my timestamp to this format but it seems like overkill with converting a LOT of times on 1 page in PHP. I could be wrong, anyone else do this in jquery but from real timestamp?
Also I currently do this in PHP on a site to show "2 hours 4 minutes ago" but wou7ld it be better to use javascript for this instead of PHP?
/*
* timeago: a jQuery plugin, version: 0.8.1 (2010-01-04)
* #requires jQuery v1.2.3 or later
*
* Timeago is a jQuery plugin that makes it easy to support automatically
* updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
*
* For usage and examples, visit:
* http://timeago.yarp.com/
* Copyright (c) 2008-2010, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
*/
(function($) {
$.timeago = function(timestamp) {
if (timestamp instanceof Date) return inWords(timestamp);
else if (typeof timestamp == "string") return inWords($.timeago.parse(timestamp));
else return inWords($.timeago.datetime(timestamp));
};
var $t = $.timeago;
$.extend($.timeago, {
settings: {
refreshMillis: 60000,
allowFuture: false,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
ago: null, // DEPRECATED, use suffixAgo
fromNow: null, // DEPRECATED, use suffixFromNow
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years"
}
},
inWords: function(distanceMillis) {
var $l = this.settings.strings;
var prefix = $l.prefixAgo;
var suffix = $l.suffixAgo || $l.ago;
if (this.settings.allowFuture) {
if (distanceMillis < 0) {
prefix = $l.prefixFromNow;
suffix = $l.suffixFromNow || $l.fromNow;
}
distanceMillis = Math.abs(distanceMillis);
}
var seconds = distanceMillis / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var years = days / 365;
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 48 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.floor(days)) ||
days < 60 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.floor(days / 30)) ||
years < 2 && substitute($l.year, 1) ||
substitute($l.years, Math.floor(years));
return $.trim([prefix, words, suffix].join(" "));
},
parse: function(iso8601) {
var s = $.trim(iso8601);
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
return new Date(s);
},
datetime: function(elem) {
// jQuery's `is()` doesn't play well with HTML5 in IE
var isTime = $(elem).get(0).tagName.toLowerCase() == 'time'; // $(elem).is('time');
var iso8601 = isTime ? $(elem).attr('datetime') : $(elem).attr('title');
return $t.parse(iso8601);
}
});
$.fn.timeago = function() {
var self = this;
self.each(refresh);
var $s = $t.settings;
if ($s.refreshMillis > 0) {
setInterval(function() { self.each(refresh); }, $s.refreshMillis);
}
return self;
};
function refresh() {
var data = prepareData(this);
if (!isNaN(data.datetime)) {
$(this).text(inWords(data.datetime));
}
return this;
}
function prepareData(element) {
element = $(element);
if (element.data("timeago") === undefined) {
element.data("timeago", { datetime: $t.datetime(element) });
var text = $.trim(element.text());
if (text.length > 0) element.attr("title", text);
}
return element.data("timeago");
}
function inWords(date) {
return $t.inWords(distance(date));
}
function distance(date) {
return (new Date().getTime() - date.getTime());
}
function substitute(stringOrFunction, value) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(value) : stringOrFunction;
return string.replace(/%d/i, value);
}
// fix for IE6 suckage
document.createElement('abbr');
document.createElement('time');
})(jQuery);

I had the same problem. I'm using Unix timestamps which are generated from PHP, so I decided to do a quick hack and extend the parsing function of jQuery timeago to handle timestamps additionally. Works like a charm. Simply look for the Parse function at around line 79 in the jquery.timeago.js file, and replace with the following:
parse: function(iso8601) {
if ((iso8601 - 0) == iso8601 && iso8601.length > 0) { // Checks if iso8601 is a unix timestamp
var s = new Date(iso8601);
if (isNaN(s.getTime())) { // Checks if iso8601 is formatted in milliseconds
var s = new Date(iso8601 * 1000); //if not, add milliseconds
}
return s;
}
var s = $.trim(iso8601);
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
return new Date(s);
},

Here is something in JavaScript using nothing but Unix timestamps.
var d1;
var d2;
d1 = (new Date()).getTime(); setTimeout( function() { d2 = (new Date()).getTime(); }, 5000 );
var secondsElapsed = (d2 - d1) / 1000;
secondsElapsed; // 5 seconds
Now, you can either store a timestamp in a JavaScript variable in the same scope as your "timeago" function, or your can store it in an HTML element. As mentioned, the time element is an HTML 5 element. You could do something like:
<p class="timestamp" style="display: none;">123456</p>
Then maybe you have a comment item like:
<div class="comment">
<p>Lorem ipsum et dolor...</p&gt
<p class="timestamp" style="display: none;">123456</p>
</div>
You could then get the timestamp for a comment by (assuming jQuery since you mentioned it):
var tstamps = $('.comment .timestamp'); // array of comment timestamps
var timeago = ( (new Date()).getTime() - tstamps[0].html() ) / 1000;
It's a bit hackish, but it would work (if I did it right).

I like to use DateJS.com which is a date / time javascript library. You can do cool stuff like this (display 2 hours ago in a <span id='myfield'></span>):
$('#myfield').text( (2).hours().ago().toString("HH:mm") );

It would be better using both, but it is not necessary to make it dynamic with JS.
In fact, I've only seen this behaviour in Facebook.
Also, are you well aware that the <time> tag is HTML5? It may create a few uncompatibilities.

Related

Timeago PHP generated element not working

I am using the timeago plugin http://timeago.yarp.com/
It seems to work if the element is generated within the html however if I try to echo it to the page from php it does not work.
Please see my files below: 1.php where you can see the issue of the correct timeago in the "load_out" div and the incorrect value (from php) in the "div2" div; showall.php; there's a basic connect.php file which connects to a database "test" containing a table "comments" - I won't inlcude it here; finally the jquery plugin which I have called timeago2.js. Please see files below:
1.php:
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="timeago2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery("abbr.timeago").timeago();
$(".div2").load('showall.php');
});
</script>
</head>
<body>
<div class="load_out" style="border:1px solid red">
<abbr class="timeago" title="2014-07-30T20:00:17Z">July 17, 2008</abbr>
</div>
<div class="div2">
<div>
</body>
</html>
showall.php
<?php
function showPosts() {
#mysql_connect("localhost","root","")or die("could not connect to mysql");
#mysql_select_db("test")or die("no database");
$me = mysql_query("SELECT * FROM comment");
while($row=mysql_fetch_array($me)){
echo '<abbr class="timeago" title="2014-07-30T20:00:17Z">hi</abbr>';
}
}
return showPosts();
?>
timeago2.js:
/**
* Timeago is a jQuery plugin that makes it easy to support automatically
* updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
*
* #name timeago
* #version 1.4.1
* #requires jQuery v1.2.3+
* #author Ryan McGeary
* #license MIT License - http://www.opensource.org/licenses/mit-license.php
*
* For usage and examples, visit:
* http://timeago.yarp.com/
*
* Copyright (c) 2008-2013, Ryan McGeary (ryan -[at]- mcgeary [*dot*] org)
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.timeago = function(timestamp) {
if (timestamp instanceof Date) {
return inWords(timestamp);
} else if (typeof timestamp === "string") {
return inWords($.timeago.parse(timestamp));
} else if (typeof timestamp === "number") {
return inWords(new Date(timestamp));
} else {
return inWords($.timeago.datetime(timestamp));
}
};
var $t = $.timeago;
$.extend($.timeago, {
settings: {
refreshMillis: 60000,
allowPast: true,
allowFuture: false,
localeTitle: false,
cutoff: 0,
strings: {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "ago",
suffixFromNow: "from now",
inPast: 'any moment now',
seconds: "less than a minute",
minute: "about a minute",
minutes: "%d minutes",
hour: "about an hour",
hours: "about %d hours",
day: "a day",
days: "%d days",
month: "about a month",
months: "%d months",
year: "about a year",
years: "%d years",
wordSeparator: " ",
numbers: []
}
},
inWords: function(distanceMillis) {
if(!this.settings.allowPast && ! this.settings.allowFuture) {
throw 'timeago allowPast and allowFuture settings can not both be set to false.';
}
var $l = this.settings.strings;
var prefix = $l.prefixAgo;
var suffix = $l.suffixAgo;
if (this.settings.allowFuture) {
if (distanceMillis < 0) {
prefix = $l.prefixFromNow;
suffix = $l.suffixFromNow;
}
}
if(!this.settings.allowPast && distanceMillis >= 0) {
return this.settings.strings.inPast;
}
var seconds = Math.abs(distanceMillis) / 1000;
var minutes = seconds / 60;
var hours = minutes / 60;
var days = hours / 24;
var years = days / 365;
function substitute(stringOrFunction, number) {
var string = $.isFunction(stringOrFunction) ? stringOrFunction(number, distanceMillis)
: stringOrFunction;
var value = ($l.numbers && $l.numbers[number]) || number;
return string.replace(/%d/i, value);
}
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
var separator = $l.wordSeparator || "";
if ($l.wordSeparator === undefined) { separator = " "; }
return $.trim([prefix, words, suffix].join(separator));
},
parse: function(iso8601) {
var s = $.trim(iso8601);
s = s.replace(/\.\d+/,""); // remove milliseconds
s = s.replace(/-/,"/").replace(/-/,"/");
s = s.replace(/T/," ").replace(/Z/," UTC");
s = s.replace(/([\+\-]\d\d)\(\d\d)/," $1$2"); // -04:00 -> -0400
s = s.replace(/([\+\-]\d\d)$/," $100"); // +09 -> +0900
return new Date(s);
},
datetime: function(elem) {
var iso8601 = $t.isTime(elem) ? $(elem).attr("datetime") : $(elem).attr("title");
return $t.parse(iso8601);
},
isTime: function(elem) {
// jQuery's `is()` doesn't play well with HTML5 in IE
return $(elem).get(0).tagName.toLowerCase() === "time"; // $(elem).is("time");
}
});
// functions that can be called via $(el).timeago('action')
// init is default when no action is given
// functions are called with context of a single element
var functions = {
init: function(){
var refresh_el = $.proxy(refresh, this);
refresh_el();
var $s = $t.settings;
if ($s.refreshMillis > 0) {
this._timeagoInterval = setInterval(refresh_el, $s.refreshMillis);
}
},
update: function(time){
var parsedTime = $t.parse(time);
$(this).data('timeago', { datetime: parsedTime });
if($t.settings.localeTitle) $(this).attr("title", parsedTime.toLocaleString());
refresh.apply(this);
},
updateFromDOM: function(){
$(this).data('timeago', { datetime: $t.parse( $t.isTime(this) ?
$(this).attr("datetime") : $(this).attr("title") ) });
refresh.apply(this);
},
dispose: function () {
if (this._timeagoInterval) {
window.clearInterval(this._timeagoInterval);
this._timeagoInterval = null;
}
}
};
$.fn.timeago = function(action, options) {
var fn = action ? functions[action] : functions.init;
if(!fn){
throw new Error("Unknown function name '"+ action +"' for timeago");
}
// each over objects here and call the requested function
this.each(function(){
fn.call(this, options);
});
return this;
};
function refresh() {
var data = prepareData(this);
var $s = $t.settings;
if (!isNaN(data.datetime)) {
if ( $s.cutoff == 0 || Math.abs(distance(data.datetime)) < $s.cutoff) {
$(this).text(inWords(data.datetime));
}
}
return this;
}
function prepareData(element) {
element = $(element);
if (!element.data("timeago")) {
element.data("timeago", { datetime: $t.datetime(element) });
var text = $.trim(element.text());
if ($t.settings.localeTitle) {
element.attr("title", element.data('timeago').datetime.toLocaleString());
} else if (text.length > 0 && !($t.isTime(element) && element.attr("title"))) {
element.attr("title", text);
}
}
return element.data("timeago");
}
function inWords(date) {
return $t.inWords(distance(date));
}
function distance(date) {
return (new Date().getTime() - date.getTime());
}
// fix for IE6 suckage
document.createElement("abbr");
document.createElement("time");
}));
jQuery(document).ready(function() {
jQuery("time.timeago").timeago();
});
important <time> span!
<time class="timeago" datetime="2008-07-17T09:24:17Z" title="July 17, 2008">8 years ago</time>
which yields: 8 years ago. As time passes, the timestamps will automatically update

Loop timer with PHP

I have a WEBVTT file connect with a video, the video length is about 120 minutes. The thumbnail tooptips of the video is running every second, which mean 120*60=7200 secs.
How to convert 7200 secs to WEBVTT format(hh:mm:ss.ttt) with php loop function? Example:
00:00:00.000 --> 00:00:01.000
00:00:01.000 --> 00:00:02.000
00:00:02.000 --> 00:00:03.000
00:00:03.000 --> 00:00:04.000
and so on...
Thanks!
Using date():
date_default_timezone_set('UTC'); // To fix some timezone problems
$start = 0; // 0h
$end = 7200; // 2h
$output = '';
for($i=$start;$i<$end;$i++){
$output .= date('H:i:s', $i).'.000 --> '.date('H:i:s', $i+1).'.000'.PHP_EOL;
}
echo $output;
Note that if $limit reaches 86400 it will start from 0 again.
I don't think PHP is the right tool here. Sounds like Javascript is probably what you're after if you want to display this on the screen for your users.
For PHP, you can use the date function
function secondsToWebvtt($seconds) {
//set the time to midnight (the actual date part is inconsequential)
$time = mktime(0,0,0,1,2,2012);
//add the number of seconds
$time+= $seconds;
//return the time in hh:mm:ss.000 format
return date("H:i:s.000",$time);
}
With Javascript, I would use a function like this
var seconds = 0;
function toTime() {
var time = new Date("1/1/2012 0:00:00");
var newSeconds = time.getSeconds() + seconds;
var strSeconds = newSeconds + "";
if(strSeconds.length < 2) { strSeconds = "0" + strSeconds; }
var hours = time.getHours() + "";
if(hours.length < 2) { hours = "0" + hours; }
var minutes = time.getMinutes() + "";
if(minutes.length < 2) { minutes = "0" + minutes; }
var dispTime = hours + ":" + minutes + ":" + strSeconds + ".000";
return dispTime;
}
function getTime() {
var time = toTime(seconds);
//do something with time here, like displaying on the page somewhere.
seconds++;
}
And then use setInterval to call the function
setInterval("getTime",1000);

JavaScript countdown from php timestamp difference

I'd like to countdown time which is difference between two time from php, the result is timestamp.
{var $time = new \DateTime()}
<div class="date" data-date="{= ($time2->getTimestamp() - $time->getTimestamp())*1000}">
In data-date I have difference of time [timestamp]. Now I want to countdown this time. I get this information from HTML to JS.
$(function() {
$(".date").each(function(){
time = $(this).data('date');
$.countdown($(this).children(".countdown"), time);
});
});
There is taken code which doesn't work properly.
jQuery.countdown = function(selector, datevalue) {
var amount = datevalue;
// catch past dates
if(amount < 0){
$(selector).html("Done");
}
// date is in the future, calculate the diff
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
//if(days != 0){out += days +" day"+((days!=1)?"s":"")+", ";}
//if(days == 0) {
if(days != 0 || hours != 0){out += ((hours<10)?"0":"") + hours +":";}
if(days != 0 || hours != 0 || mins != 0){out += ((mins<10)?"0":"") + mins +":";}
out += ((secs<10)?"0":"") + secs;
$(selector).html(out);
//}
// run it all again
setTimeout(function() {
$.countdown(selector, datevalue);
}, 1000);
}
};
The time from JS is on the right place but it doesn't countdown.
The answer is very simple: you do not decrease datevalue variable. So its the same for all iterations
Look at the example below it works fine
jQuery.countdown = function(selector, datevalue) {
var amount = datevalue;
// catch past dates
if(amount < 0){
$(selector).html("Done");
}
// date is in the future, calculate the diff
else{
datevalue--;
$(selector).html(datevalue);
setTimeout(function() {
$.countdown(selector, datevalue);
}, 1000);
}
};
$.countdown('.date', 10);​​​

Countdown timer built on PHP and jQuery?

After spending the last 45 minutes looking around for a solution, I can't seem to find an easy solution to creating a countdown timer using PHP and jQuery. Most already built scripts I've found are based purely on jQuery which require a ton of code, and more parameters then they should, plus, adaptability is pretty hard.
Here's my situation;
PHP:
$countdown = date("h:i:s"); // This isn't my actual $countdown variable, just a placeholder
jQuery:
$(document).ready(function name() {
$("#this").load( function() {
setTimeout("name()", 1000)
}
}
});
HTML:
<div id="this"><?php echo($countdown); ?></div>
My idea is that, every second, #this is reloaded, giving a new value to it's contents, and as $countdown isn't a static variable, a new value will be loaded each time. This removes the need to deal with sessions (as a basic javascript countdown timer would reset on pageload, etc).
I would've though this would have worked, until I realized that the event binder .load() doesn't reload #this (I know silly me), so I guess what I'm wondering is - is there an event binder I can use to make this work or is there a way to get the functionality I'm looking for, without using a jQuery plugin (which doesn't match exactly what I want anyway)?
You should use Keith Wood's countdown timer: http://keith-wood.name/countdown.html
It is extremely easy to use.
All you have to do is
$('#timer').countdown({
until: '<?php echo date("h:i:s"); ?>' // change this, obviously
});
Here's the fiddle: http://jsfiddle.net/tqyj4/289/
OK, I know that an id is not a variable, but don't use this as an ID. It is makes people cringe.
To the rest, don't reload the value, set a value in JS in PHP and then count down.
// place this in the <head> above the code below
echo "var t = " . time() . ";";
echo "var ft = " . /* your final time here */ . ";";
Then:
// this is a helper function.
function lpad( input, len, padstr )
{
if( !padstr ) padstr = " "; // this is the normal default for pad.
var ret = String( input );
var dlen = ret.length - len;
if( dlen > 0 ) return ret;
for( var i = 0; i < dlen; i++ ) ret = padstr + ret;
return ret;
}
$(document).ready(function name() {
$("#timer").load( function() { // I changed the id
$timer = $("timer"); // might as well cache it.
// interval, not timeout. interval repeats
var intval = setInterval(function(){
t += 500; // decrease the difference in time
if( t >= ft )
{
t = ft; // prevent negative time.
clearInterval( intval ) // cleanup when done.
}
var dt = new Date(ft - t);
$timer.innerHTML = dt.getHours() + ":" +
// pad to make sure it is always 2 digits
lpad( dt.getMinutes(), 2, '0' ) + ":" +
lpad( dt.getSeconds(), 2, '0' );
}, 500) // increments of .5 seconds are more accurate
}
}
});
Once php has loaded a particular amount of time for the user, can you explain why this wouldn't be sufficient for your needs:
$(function(){
$timerdiv = $("#this");
timer();
});
function timer()
{
$timerdiv.html((int)$timerdiv.html() - 1);
setTimeout(timer, 1000);
}
You are very close in your original code. Here's a modification to your code below that works as described, or at least so I think - I know it works, but am not sure if it meets your requirements, they were a little unclear. Obviously if you reload the page, you would have to rely on the PHP output to be different in order for the counter to not reset. Just to note though, I'm not entirely sure why you would use the .load function - that function is really just a wrapper for an AJAX call to grab the contents of another page and insert it into the selected div. I believe what you're looking for is the .html() function to change the contents of the selected div using the content available in the DOM vs. making an AJAX request.
var timer;
$(document).ready(
name();
);
function name() {
//clear the timer
clearTimeout(timer);
//reset the timer
timer = setTimeout("name()", 1000);
//grab the current time value in the div
var time = $("#this").html();
//split times
var time_splits = time.split(":");
//add up total seconds
var total_time = (parseInt(time_splits[0])*60*60) + (parseInt(time_splits[1])*60) + parseInt(time_splits[2]);
//subtract 1 second from time
total_time -= 1;
//turn total time back in hours, minutes, and seconds
var hours = parseInt(total_time / 3600);
total_time %= 3600;
var minutes = parseInt(total_time / 60);
var seconds = total_time % 60;
//set new time variable
var new_time = (hours < 10 ? "0" : "") + hours + (minutes < 10 ? ":0" : ":" ) + minutes + (seconds < 10 ? ":0" : ":" ) + seconds;
//set html to new time
$("#this").html(new_time);
}
$dateFormat = “d F Y — g:i a”;
$targetDate = $futureDate;//Change the 25 to however many minutes you want to countdown change date in strtotime
$actualDate = $date1;
$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);
<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(statusfun)
{//alert(seconds);
var SD;
if(days >= 0 && minutes >= 0){
var dataReturn = jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdowncont/’; ?>”,
async: true,
success: function(data){
var data = data.split(“/”);
day = data[0];
hours = data[1];
minutes = data[2];
seconds = data[3];
}
});
seconds–;
if (seconds < 0){
minutes–;
seconds = 59
}
if (minutes < 0){
hours–;
minutes = 59
}
if (hours < 0){
days–;
hours = 23
}
document.getElementById(“remain”).style.display = “block”;
document.getElementById(“remain”).innerHTML = ” Your Product Reverse For “+minutes+” minutes, “+seconds+” seconds”;
SD=window.setTimeout( “setCountDown()”, 1000 );
}else{
document.getElementById(“remain”).innerHTML = “”;
seconds = “00″; window.clearTimeout(SD);
jQuery.ajax({
type: “GET”,
url: “<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).’index.php/countdown/’; ?>”,
async: false,
success: function(html){
}
});
document.getElementById(“remain”).innerHTML = “”;
window.location = document.URL; // Add your redirect url
}
}
</script>
<?php
if($date1 < $futureDate && ($qtyCart > 0)){ ?>
<script type=”text/javascript”>
setCountDown();
</script>
<?php }else{ ?>
<style>
#remain{display:none;}
</style>
<?php }}?>
<div id=”remain”></div>
For more information visit urfusion
#epascarello answer for your question in you need to pass the loop value in selector with id for example
$("#timer<? php echo $loopval; ?>")
and also call the it in the
<div id="timer<?php echo $loopval; ?>">
</div>

PHP JavaScript Countdown Timer

I need to make a countdown timer that displays a specific number of minutes and seconds counting down - not a countdown to a certain date.
And depending on a variable, change these numbers.
So for $video == 1, I need to display on the page: 8 minutes & 54 seconds (counting down)
And for $video == 2, I need to display on the page: 5 minutes & 01 seconds (counting down)
I also need the countdown display to disappear after the time has elapsed, but maybe I should put that into a different question.
The problem I'm having is the all the countdown scripts I can find deal with counting down to a specific date.
Everything you need, just enter the total time in seconds in the <span> tags. 30 and 120 here for demo. Should work if you copy and paste directly into a webpage. Add and edit code as needed.
<span id="countdown-1">30 seconds</span>
<span id="countdown-2">120 seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
/**
* Countdown function
* Clock count downs to 0:00 then hides the element holding the clock
* #param id Element ID of clock placeholder
* #param timer Total seconds to display clock
*/
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
document.getElementById(id).style.display = 'none';
}
}
</script>
Try:
var x, secs = 600; //declared globally
x = setInterval(myFunc, 1000);
function myFunc()
{
document.getElementById('timer').innerHTML = secs; //assuming there is a label with id 'timer'
secs --;
if(secs == 0)
{
document.getElementById('timer').style.hidden = true;
clearInterval(x);
}
}
There is a countdown script located at http://javascript.internet.com/time-date/countdown-timer.html that doesn't countdown to a date but rather a specified amount of minutes.
The code may be customized as follows to get the desired effect
<?php
if ($video===1){
$time="8:54";
}
if ($video===2){
$time="5:01";
}
?>
<script type="text/javascript" src="countDown.js"></script>
<form name="cd">
<input id="txt" readonly="true" type="text" value="<?php echo $time; ?>" border="0" name="disp">
</form>
Make sure that the contents of countDown.js looks like this:
/* This script and many more are available free online at
The JavaScript Source :: http://javascript.internet.com
Created by: Neill Broderick :: http://www.bespoke-software-solutions.co.uk/downloads/downjs.php */
var mins
var secs;
function cd() {
mins = 1 * m("10"); // change minutes here
secs = 0 + s(":01"); // change seconds here (always add an additional second to your total)
redo();
}
function m(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(0, i));
}
function s(obj) {
for(var i = 0; i < obj.length; i++) {
if(obj.substring(i, i + 1) == ":")
break;
}
return(obj.substring(i + 1, obj.length));
}
function dis(mins,secs) {
var disp;
if(mins <= 9) {
disp = " 0";
} else {
disp = " ";
}
disp += mins + ":";
if(secs <= 9) {
disp += "0" + secs;
} else {
disp += secs;
}
return(disp);
}
function redo() {
secs--;
if(secs == -1) {
secs = 59;
mins--;
}
document.cd.disp.value = dis(mins,secs); // setup additional displays here.
if((mins == 0) && (secs == 0)) {
window.alert("Time is up. Press OK to continue."); // change timeout message as required
// window.location = "yourpage.htm" // redirects to specified page once timer ends and ok button is pressed
} else {
cd = setTimeout("redo()",1000);
}
}
function init() {
cd();
}
window.onload = init;
<?php
$countDownTime = 0;
if ($video == 1) $countDownTime = (8*60 + 54);
else if ($video == 2) $countDownTime = (5*60 + 1);
echo '<script>var countdownTime="' . $countDownTime . '";</script>"';
?>
<script>
<!-- as per the hyper linked reference below -->
$(selector).countdown({until: countdownTime});
</script>
Using the following library, you can implement a JQuery timer using the var countdownTime you specify above...
http://keith-wood.name/countdown.html <-- tutorial on the first page!
Edit Replaced $someTimeInSeconds with $countDownTime
Ok, I'm looking at doing something similar. Currently I have a simple countdown timer that is based off of current time that counts down every 30min. The problem is that I have to use a meta refresh to update it. I'm wondering if a combination of javascript and PHP might be a simpler solution to this answer. Use javascript to call the php code and automatically update it? Maybe set a variable for the time in the php script to be called with javascript? Well, here's the code I have that might help. I'm still learning.
$minutes_left = ($minutes)?((30 - $minutes)-(($seconds)?1:0)):0;
$minutes_left = str_pad ($minutes_left , 2, '0', STR_PAD_LEFT);
$seconds_left = ($seconds)?(60 - $seconds):0;
$seconds_left = str_pad ($seconds_left , 2, '0', STR_PAD_LEFT);
echo '<center><h1 style="font-color:white;">Next station break in: '.$minutes_left.'m '.$seconds_left.'s</h2></center>';
?>
I just have to figure out how to get it to reset itself at the end of every 30min and to update without meta refresh.

Categories