UTC clock based on server time? - php

I have a JavaScript clock that gets the time in UTC, it currently works, but the time is based off the client's computer. What could I do to base the time off of the server instead? I am using PHP as the server scripting language. I would like to not use AJAX.
<?php
$year = date("Y");
$month = date("m");
$day = date("d");
$hour = date("h");
$minute = date("i");
$str = $year . $month . $day . $hour . $minute;
echo "history.pushState('', 'title', '?q=$str');";
echo "var ct = '$str';";
?>
function dT(){
var d = new Date();
d = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
d.setTime(d.getTime());
v = d.getFullYear() + "" +
padstr(d.getMonth()) + "" +
padstr(d.getDate()) + "" +
padstr(d.getHours()) + "" +
padstr(d.getMinutes()) + "" + padstr(d.getSeconds());
if(ct !== v){
history.pushState('', 'title', '?q=' + v);
ct = v;
}
setTimeout('dT()', 1000);
}
dT();
Edit
var a = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
document.getElementById("time").innerHTML = a;
function clock_tick(){
var time = moment(a);
time.add('second', 1);
a = time.format("YYYY-MM-DD HH:MM:SS");
document.getElementById("time").innerHTML = a;
setTimeout("clock_tick()", 1000);
}
clock_tick();

This should get you started. You don't need to use moment.js, but I wanted to try it out since someone suggested it.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="moment.js"></script>
<script language="javascript">
$(function() {
$('#clock')[0].innerHTML = moment().format("<?php echo date("Y-m-d H:i:s", time()); ?>");
clock_tick();
});
function clock_tick(){
var clock_div = $('#clock')[0];
var time = moment(clock_div.innerHTML);
time.add('second', 1);
clock_div.innerHTML = time.format("YYYY-MM-DD hh:mm:ss");
setTimeout("clock_tick()", 1000);
}
</script>
</head>
<body>
<div id="clock"></div>
</body>
</html>
Then as I stated earlier you may need to set:
date_default_timezone_set("UTC");
Reference Link:
http://php.net/manual/en/function.date.php

moment(give ur value).format('L');
that will returns the local time. see the below url it got lots of formatting options, will fit your needs.
http://momentjs.com/

Related

How to count time from list of timestamps in PHP?

I want to count time spent on the website. I have a list of timestamps for each user, the smallest interval between each timestamp is at least 60 seconds.
Edit:
Here is my code, can't group them by range of 100 seconds
<?php
$numbers = array(1503541542,1503541602,1503541662,1503541722,1503541782,1503541842,1503541902,1503541962,1503542022,1503542082,1503542142,1503542202,1503542262,1503542322,1503542382,1503542442,1503542502,1503542562,1503542622,1503542682,1503542742,1503542798,1503542799,1503542859,1503542877,1503542878,1503542938,1503542961,1503542962,1503543022,1503543079,1503543080,1503543140,1503543200,1503543221,1503543221,1503543281,1503543341,1503543401,1503543461,1503543521,1503543581,1503543641,1503543701,1503543761,1503543821,1503543881,1503543941,1503544001,1503544061,1503544121,1503544181,1503544241,1503544301,1503544361,1503544421,1503544481,1503544541,1503544601,1503544661,1503544721,1503544781,1503544841,1503544901,1503545055,1503545056,1503545060,1503545061,1503545120,1503545173,1503545174,1503545181,1503545233,1503545240,1503545293,1503545301,1503545304,1503545304,1503545364,1503545424,1503545484,1503545544,1503545604,1503545664,1503545724,1503545784,1503545844,1503545904,1503545964,1503546024,1503546084,1503546144,1503546204,1503546264,1503546324,1503546358,1503546359,1503546419,1503546479,1503546539,1503546599,1503546659,1503546719,1503546779,1503546839,1503546899,1503546959,1503547019,1503547079,1503547139,1503547167,1503547167,1503547199,1503547218,1503547218,1503547254,1503547254,1503547259,1503547281,1503547282,1503547319,1503547340,1503547341,1503547379,1503547401,1503547439,1503547461,1503547499,1503547521,1503547559,1503547581,1503547619,1503547641,1503547679,1503547701,1503547739,1503547761,1503547799,1503547821,1503547859,1503547881,1503547919,1503547941,1503547979,1503548001,1503548039,1503548061,1503548099,1503548121,1503548159,1503548181,1503548219,1503548240);
// $numbers = array(10, 30, 230, 240, 250, 260);
$result = array();
while (count($numbers) > 0) {
$begin = reset($numbers);
$end = array_shift($numbers);
while (in_array($end + 100, $numbers)){
$end = array_shift($numbers);
}
$beginAndEnd = array_unique(array($begin, $end));
$result[] = implode('-', $beginAndEnd);
}
print_r($result);
?>
Thank you in advance
The Best way to get user time stamps on a particular website is to use function "load" and "onunload", below is the code :
<!DOCTYPE html>
<html>
<head>
<title>Collect time</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function()
{
var start = null;
$(window).load(function(event) {
start = event.timeStamp;
});
$(window).onunload(function(event) {
var time = event.timeStamp - start;
$.post('/collect-user-time/ajax-backend.php', {time: time});
})
});
</script>
</head>
<body>
</body>
</html>
And backend script:
<?php
$time = intval($_POST['time']);
if (!file_exists('data.txt')) {
file_put_contents('data.txt', $time . "\n");
} else {
file_put_contents('data.txt', $time . "\n", FILE_APPEND);
}
Hum, your question is unclear but if I understand, this is my idea :
Add 2 session variables :
1 var to register old page on reload and update it on reload
1 var to register timestamp and update it on reload
Look this :
if(isset($_SESSION['page']) && isset($_SESSION['timestamp'])){
//REGISTER WHERE YOU WANT : BDD, LOGFILE...
//$userStay=$db->prepare();
//fopen('userStay', 'a+');
//WITH THESE DATA
$time = time() - $_SESSION['timestamp'];
$page = $_SESSION['page'];
}
$_SESSION['page']=$_SERVER['REQUEST_URI'];
$_SESSION['timestamp']=time();

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);

Creating Timer for an auction website

I am trying to create a timer for an auction website.
Each product has a specific end date called TargetDate, which is entered in TimerInput.php file.
These values are then posted into TimerOutput.php file which will display the product followed by the timer countdown to finish date.
Each time the counter > 15 and the user click on bid button, the timer continue countdown normally.
But when the counter < 15, each time clicking bid causes the timer to reset to 15 by extending the TargetDate by the specific value related to when the button was pressed.
First, the Bid button wasn't working, so instead the function is called by refreshing the page.
When the timer is under 15, refreshing the page causes the TargetDate to be extended as it should be and the timer is reset to 15.
But the problem is when the first TargetDate entered originally in TimerInput.php file is reached, the bid is over, although showing different time during execution of code shows that the date is being updated.
I have tried to works by executing the code in PHP alone and displaying using Javascript.
Then I have tried to execute code by Javascript and finally I have tried to write the date into external file and read it again but with no result.
Thanks for any help in advance.
Here is my code:
TimerOutput.php:
<?php
// target date entered by user
$TargetDate = $month."/".$day."/".$year." ".$hour.":".$minute.":".$second." ".$hourclock;
// change target date to unix timestamp format
$UnixTargetDate = strtotime($month."/".$day."/".$year." ".$hourHC.":".$minute.":".$second);
// unix timestamp right now
$unixtime = strtotime("now");
}
?>
<script language="JavaScript">
//TargetDate = "7/30/2012 13:32";
ForeColor = "navy";
CountActive = true;
CountStepper = -1;
LeadingZero = true;
DisplayFormat = "%%H%%:%%M%%:%%S%%";
FinishMessage = "Sold at: "
// extract timer variables inputs
var unixNow = parseInt("<?php echo $unixtime?>");
var unixTarget = parseInt("<?php echo $UnixTargetDate?>");
function AdditionalSecond()
{
if ((unixTarget - unixNow)>0 && (unixTarget - unixNow)<15)
{
// reset timer to 15s
// update target date
unixTarget = unixTarget + 15 - (unixTarget - unixNow);
}
else if ((unixTarget - unixNow)>15)
{
// do nothing continue countdown normally
unixTarget=unixTarget;
}
else
{
// display that item is sold when time is up
FinishMessage
}
}
// call function AdditionalSecond() to be executed
AdditionalSecond();
// create a new javascript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds
var date = new Date(unixTarget*1000);
// month part from the timestamp
var months = date.getMonth()+1;
// day part from the timestamp
var days = date.getDate();
// year part from the timestamp
var years = date.getFullYear();
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
TargetDate = months + '/' + days + '/' + years + ' ' + hours + ':' + minutes + ':' + seconds;
</script>
<div id="countTimer" name="countTimer" style="margin-left:100px;">
<script language="JavaScript" src="countdown.js"></script>
</div>
<div id = "soldtime" style = "margin-left:100px;">
<span id="timedispspan"></span>
</div>
<div id = "bottom" style = "margin-left:100px;">
<form name="BidForm" id="BidForm" onsubmit="return false">
<input type="button" value="Bid" onclick="AddSecond();" style = "width:100px;height:30px;">
</form>
</div>
</body>
</html>
countdown.js:
function calcage(secs, num1, num2) {
s = ((Math.floor(secs/num1))%num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function refreshDiv(){
document.getElementById("cntdwn").innerHTML = DisplayStr;
}
function CountBack(secs) {
if (secs < 0) {
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));
document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor) {
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}
if (typeof(BackColor)=="undefined")
BackColor = "white";
if (typeof(ForeColor)=="undefined")
ForeColor= "black";
if (typeof(TargetDate)=="undefined")
TargetDate = "12/31/2012 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
CountActive = true;
if (typeof(FinishMessage)=="undefined")
FinishMessage = "";
if (typeof(CountStepper)!="number")
CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
ddiff = new Date(dnow-dthen);
else
ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);

time between a date and a unix time, and a timer counting down that time

As my title sais I want to make a timer that counts down the time between a unix time of the current time and a date (including hour minute and secounds) in js.
I don't have idea how to do it can you give me some help here?
var now = new Date();
var date = new Date(2012, 7, 9);
var diff = new Date(date - now);
var res = '';
res += diff.getHours() + 'h ';
res += diff.getMinutes() + 'min ';
res += diff.getSeconds() + 's';
See it in action on JS Bin
var timestamp = new Date(2012,6,8,13,54,52).getTime()-new Date().getTime();
// 0 based month
var tid = setInterval(
function() {
if (timestamp<=0) clearIntervaltid);
document.getElementById("timeContainer").innerHTML=new Date(timestamp-=1000);
},1000);
This countdown also handles negative times (countdown reached).
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var zeroDate_ms = Date.parse("8 Jul 2012 22:41:00 GMT+2");
window.setInterval("countdown()", 1000);
function countdown() {
var now_ms = Number(new Date());
var sign = (zeroDate_ms < now_ms) ? "-":"";
var diff_s = Math.floor(Math.abs(zeroDate_ms - now_ms)/1000);
var diff_h = Math.floor(diff_s / 3600/*1000*60*60*/);
diff_s -= (diff_h * 3600);
var diff_m = Math.floor(diff_s / 60/*1000*60*/);
diff_s -= (diff_m * 60)
var h = String(diff_h);
var m = ("0"+String(diff_m)).substr(-2);
var s = ("0"+String(diff_s)).substr(-2);
document.getElementById("countdown").innerHTML=sign+h+":"+m+":"+s
}
</script>
</head>
<body>
<div id="countdown"></div>
</body>
</html>

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>

Categories