Elapsed time from a given time in the database - php

I have a HTML table which has records pulled in from the database. I'm using PHP/MySQL.
The Column in my table named "Timer" is not retrieved from the database. I need the elapsed time (from the a specific time in the database) to be shown here. For Example, let's say the time now is 21 Feb 2013 6.20 pm and the time in the database is 21 Feb 2013 5.50 pm, I need the Timer Column to Display 00:30:00 (as thirty minutes have passed since 5.50PM). It must be a Running timer (Not a static one which can be computed by using MySQL datetime difference) so whoever accesses the page should be able to see the same elapsed time. I also need to stop the timer when I click another button.
I saw other posts here related to this question like this Elapsed Time to database from Javascript timer but I think what I'm asking is different. I'm still confused on how to go about doing this. I've very little Javascript knowledge, would be greatful if you could help me with it or refer me to the right place. Thank you!

This can be achieved with very little Javascript.
Assuming that the "Created" time is rendered dynamically in the table with format dd MMM yyyy hh:mm:ss, something like this should do the trick:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
ElapsedTimeLogger = function(dateElementId, elapsedElementId, interval) {
var container = $(elapsedElementId);
var time = parseDate($(dateElementId).text());
var interval = interval;
var timer;
function parseDate(dateString) {
var date = new Date(dateString);
return date.getTime();
}
function update() {
var systemTime = new Date().getTime();
elapsedTime = systemTime - time;
container.html(prettyPrintTime(Math.floor(elapsedTime / 1000)));
}
function prettyPrintTime(numSeconds) {
var hours = Math.floor(numSeconds / 3600);
var minutes = Math.floor((numSeconds - (hours * 3600)) / 60);
var seconds = numSeconds - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
var time = hours + ":" + minutes + ":" + seconds;
return time;
}
this.start = function() {
timer = setInterval(function() {update()}, interval * 1000);
}
this.stop = function() {
clearTimeout(timer);
}
}
$(document).ready(function () {
var timeLogger = new ElapsedTimeLogger("#date", "#elapsed", 2);
timeLogger.start();
$("#stop_timer").click(function() {
timeLogger.stop();
});
$("#start_timer").click(function() {
timeLogger.start();
});
});
</script>
</head>
<body>
<table border="1">
<tr><th>Created</th><th>Timer</th></tr>
<tr><td id="date">21 Feb 2013 12:30:00</td><td id="elapsed"></td></tr>
</table>
<input id="stop_timer" type="button" value="Stop timer"></input>
<input id="start_timer" type="button" value="Start timer"></input>
</body>
</html>
Copy the code above into a file, say index.html, and open it in a browser. I tested it on Chrome.
It should update the elapsed time every 2 seconds, but you may change the update interval to something that suits you, e.g. to make it update every 5 minutes:
new ElapsedTimeLogger("#date", "#elapsed", 300);
The general concept is to parse the rendered "Created" date into an epoch timestamp (in milliseconds) and then compute its difference with the current system time. To get the elapsed time updating dynamically you use Javascript's setInterval function. To stop updating the elapsed time use Javascript's clearTimeout function.
I lifted the prettyPrintTime function from powtac.

If you are looking for a pure html base solution with the sql to do the dynamic changes, it is impossible. If you need to do a running timer you will need to use JS. (can be done with the help of css5 as well).

You'd want to use PHP to retrieve the time from the database, then use Javascript to display a timer that's counting from the time retrieved. You should be able to find available premade Javascript scripts that can do this quite easily. Here's one I found. I have no idea if it's the best for your needs, but it was amongst the first results. Just snip off the parts not needed, like the year, month, etc.
http://praveenlobo.com/techblog/javascript-countup-timer/

Related

How to use offsets for time zones with php?

I just don't understand GMT on how it works with your php sql server time. How do you relate to your database with the minutes offset? So if this produces -420 minutes how do we relate that to our database time (for example unix time 2016-09-14 22:40:31)(your NOW() time)?
I am just not sure how to implement this in PHP? There is some vague information I have found on how to use it after you get your minutes offset.
`date_default_timezone_set('America/Boise');`
$created=date('Y-m-d H:i:s');
I got the code below from:
https://stackoverflow.com/a/5492192/6173198
function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
//go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
//To ignore daylight saving time look for the lowest offset.
//Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
alert(TimezoneDetect());
You can use the bellow code to set the time zone:
date_default_timezone_set('Europe/London');
This code will add +1 hour onto the timestamp.
$timestamp= strtotime("+1 hour");
I hope this is what you were asking for.
You can also use the same as what you were using to turn the timestamp into text:
gmdate("H:i", $timestamp);

Using jquery countdown timer with mysql datetime?

I know this question has been asked many times as I have found a few on google and also on stackoverflow.
but none of them explained how to format my datetime in my php so it works in combination with jquery countdown timer. so I am going to ask it here in a hope i get someone shed a light on this for me.
Basically what i am trying to do is to create a countdown timer which will work with mysql datetime.
the datetime is stored in mysql so All need to do is to get the correct format in my php so the countdown timer could work with it.
I am using this plugin: http://keith-wood.name/countdown.html
and here is what i have so far:
PHP formatting:
$end_date = date("m d Y H:i:s T", strtotime($row["end_date"]));
Jquery/Javascript code:
<script type="text/javascript">
$(function(){
var countdown = $('#countdown'),
ts = new Date(<?php echo $end_date * 1000; ?>),
finished = true;
if((new Date()) > ts)
{
finished = false;
}
$('#defaultCountdown').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);
}
});
});
</script>
when i run this code, all i get is 0 hours, 0 minutes, 0 seconds.
I can only suspect that the issue is from formatting the datetime in my php section!
or am i missing something else as well?
okay I have managed to minify the code to this:
<script type="text/javascript">
$(document).ready(function () {
$('#defaultCountdown').countdown({
until: new Date(<?php echo $end_date; ?>),
compact: true
});
});
</script>
and changed the php to this:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
However, the time shown in the coutdown timer is wrong (way off).
the $end_date is: September 22 2013 23:30:00 GMT in mysql datetime
but the jquery countdown timer is showing:
34d 06:21:48
2013, 9, 22, 23, 30, 00
34days and 6 hours blah blah is absolutely wrong!
what am i doing wrong here now?
The JavaScript Date object is constructed as follows:
Date(year, month, day, hours, minutes, seconds, milliseconds)
That means you probably should be doing something along these lines:
$end_date = date("Y, n, j, G, i, s", strtotime($row["end_date"]));
Sources:
JavaScript Date-object
PHP date-function
EDIT:
In addition, I seem to have found the problem in the jQuery Countdown manual:
A note on Date - the JavaScript Date constructor expects the year,
month, and day as parameters. However, the month ranges from 0 to 11.
To make explicit what date is intended (does a month of 3 mean March
or April?) I specify the month from 1 to 12 and manually subtract the
1. Thus the following denotes 25 December, 2010.
So, you'd have to split the string, substract 1 from the month and rebuild...
$tmp_date = explode(', ', $end_date);
$tmp_date[1] = $tmp_date[1] - 1;
$end_date = implode(', ', $tmp_date);
Link to jsFiddle

calculate time difference and display popup based on time difference

im writing a small calendar based on php and jquery which has the a function to calculate the time difference and display a popup 15 minutes before.
Can some one tell me how can i calculate the time difference in minutes and popup 15 minutes before.
my time is saved as
18-07-2012 15:13:54
jsBin demo
var php = '19-07-2012 03:00:00'.split('-');
var phpDate = php[1]+'/'+php[0]+'/'+php[2];
var phpTime = new Date(phpDate).getTime();
var currTime = new Date().getTime();
var difference= phpTime-currTime;
var leftMin = Math.ceil( difference/(1000*60) );
$('#test').text(leftMin+' MINUTES LEFT!');
Code explanation:
To get the remaining time I've done a millisecond comparison of the php returned time in milliseconds from Jan. 1 1970
and the current time in ms from Jan 1 1970 - subtracting the two values and getting the milliseconds difference. To calculate that difference in minutes I've just done:
var leftMin = Math.ceil( difference/(1000*60) );
The trick was to get the right time format and to revert your (php) returned time to that format too.
The default format looks like: MONTH/DAY/YEAR HOURS:MINUTES:SECONDS
To convert the php returned time '19-07-2012 03:00:00'to that one, I used:
var php = '19-07-2012 03:00:00'.split('-'); // split in array fractions
var phpDate = php[1]+'/'+php[0]+'/'+php[2]; // reposition array keys and add '/'
which returns: 07/19/2012 03:00:00 and now we can compare it to the current time e.g.:
07/19/2012 03:45:21
To retrieve the ms from your converted php time we can use:
var phpTime = new Date(phpDate).getTime(); // get "ms from our string
and for the current time we just take:
var currTime = new Date().getTime(); // get "ms from 1/1/1970
Now having our two milliseconds values we can simply subtract them to get the remaining time:
var difference= phpTime-currTime;
Check PHP's DateTime::diff! Maybe it helps you.
var dateStr = '18-07-2012 15:13:54'//Day-Month-Year
var dateArray = dateStr.split('-')
var d1 = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2])
var dateStr2 = '18-07-2012 14:10:54'//Day-Month-Year
var dateArray2 = dateStr2.split('-')
var d2 = new Date(dateArray2[1]+'-'+dateArray2[0]+'-'+dateArray2[2])
var minutes = (d1-d2)/1000/60
-edit; revised code below:-
function timeDiff(date1, date2){
//date format: Day-Month-Year
var dateArray = date1.split('-')
var d1 = new Date(dateArray[1]+'-'+dateArray[0]+'-'+dateArray[2])
var dateArray2 = date2.split('-')
var d2 = new Date(dateArray2[1]+'-'+dateArray2[0]+'-'+dateArray2[2])
var minutes = (d1-d2)/1000/60
return minutes;
}
if(timeDiff('18-07-2012 15:13:54', '18-07-2012 14:59:54')<=15){
alert('popup')
}
php has an mktime() function (http://php.net/manual/en/function.mktime.php) which takes in a hours, minutes, seconds, month, day, year and calculates the seconds since the epoch (in like 1971). Then you can subtract 15*60 use the date() function to go from seconds back to a date format. (http://php.net/manual/en/function.date.php)

How to turn php time function into javascript function?

I'm not that good at javascript (yet), so I need some help, with an alternative version of this php script (In javascript)
function until($format = ""){
$now = strtotime("now");
$nextTuesday = strtotime("-1 hour next tuesday");
$until = $nextTuesday - $now;
if(empty($format)){
return $until;
}else{
return date("$format",$until);
}
}
Just need it to count down, until next tuesday, in a really short way (Not in 20+ lines, like all the other script I've seen)
It should still return a timestamp, if it's possible (Need it for an offline app)
So if anyone could help me, I would be really happy (Not that I'm not happy right now, but I would be even happier) :D
You may want to take a look at the phpjs site. They have code showing how a substantial number of PHP functions can be done in JS.
Specifically: strtotime and date
JS doesn't have anything remotely close to strtotime. You'd have to determine "next tuesday" yourself. Once you've got that, you can extract a timestamp value using .getTime(), which will be the number of milliseconds since Jan 1/1970. This value can also be fed back into a new date object as a parameter, so you can do date math using simple numbers externally, then create a new date object again using the result.
e.g.
var now = new Date();
var ts = now.getTime();
var next_week = ts + (86400 * 7 * 1000);
next_week_object = new Date(next_week);
Once you've got the "next tuesday" code figured out, the rest is trivial
To get milliseconds till the next tuesday (nearest in the future):
function f_until(){
var now = new Date(Date.now());
var nextT = new Date(Date.now());
var cD = nextT.getDay();
if(cD < 2)nextT.setDate(nextT.getDate() + (2-cD));
else nextT.setDate(nextT.getDate() + (9-cD));
nextT.setHours(nextT.getHours() - 1);
//alert('next tuesday: '+nextT.toString());
return nextT.getTime() - now.getTime();
}

how to modify this javascript time function to show hours less than ten as: 0x

//Live Javascript Server Time
function getthedate(){
var mydate=new Date()
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn="AM"
if (hours>=12)
dn="PM"
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
var cdate="<strong><font color='b9b9b9' size='1'> "+hours+":"+minutes+":"+seconds+" "+dn+"</font></strong>"
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function live_servertime(){
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
Does this display the live SERVER time? If not, any ideas how to achieve this?
Also I'm stumped on how to modify it to put a zero in front of hours that are less than ten?
If you understand how the minutes and seconds get the leading zero, it should be pretty obvious.
if (hours==0)
hours=12
if (hours <= 9) // <--
hours = "0" + hours; // <--
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
and no, new Date() just gets the time from the client.
Hint: look at how minutes and seconds get a leading zero.
if (minutes<=9)
minutes="0"+minutes
No, it doesn’t display the server time. I can’t, because it runs entirely on the client (browser) and doesn’t communicate with the server.
To put a 0 in front of the single-digits hours, just do the same that you’re already doing with the minutes and secconds:
if (hours <= 9)
hours = "0" + hours;

Categories