I have a digital clock made with jQuery, it displays current exact time from the client machine, it works perfectly, BUT I want to make it display the exact time from the server and not the client.
How it works it updates every 1000ms (1 second) and every time retrieves the current hour:minute:second
Now is there a way to make a HTTP request to a PHP script (/get-time.php) and display the exact server time? Of course it's not a good practice to make a HTTP request every second to get the new time for every visitor, so is there a way to make it even every 10 seconds to correct the time and keep the clock ticking every second like a real digital clock?
This is the HTML:
<div class="digital-clock float-right">00:00:00</div>
This is the jQuery code:
$(document).ready(function() {
clockUpdate();
setInterval(clockUpdate, 1000);
});
function clockUpdate() {
var date = new Date();
$('.digital-clock').css({'color': '#fff', 'text-shadow': '0 0 3px #ff0'});
function addZero(x) {
if (x < 10) {
return x = '0' + x;
} else {
return x;
}
}
function twelveHour(x) {
if (x > 12) {
return x = x - 12;
} else if (x == 0) {
return x = 12;
} else {
return x;
}
}
var h = addZero(twelveHour(date.getHours()));
var m = addZero(date.getMinutes());
var s = addZero(date.getSeconds());
$('.digital-clock').text(h + ':' + m + ':' + s)
}
Related
This is for a game that I am considering.
I have a point that is noted as moving inside a (2D) circle from an arbitrary point, at an arbitrary direction and at a particular time. The point will bounce off the interior wall of the circle when it intersects.
For this example let's say the circle has a diameter of 100 kilometers with it's center at (0,0) and 10 hours ago the point was at location (20,30) with a heading of 40 degrees at a speed of 50kph .
What is the best way to determine where that point currently is and at what direction it's traveling?
I will be implementing this in PHP with the point and circle data stored in MySQL. Since it is a web page there will be no constantly running host process to keep things up to date and the data will need to be refreshed upon a page load.
I'm certainly not looking for anyone to write the code for me but am hoping someone can help me with a somewhat efficient way to approach this.
Your point-object will travel along what is called chords in geometry.
As the object hits the circle boundary, it will reflect from the circle's tangent at that point, and go along a next chord that has the same length. The next hit will be at the same angle (with the tangent at that hit point) as the previous hit, and so it will continue. At a constant speed, the time between hits will be a constant time.
Given the start time and the current time, one can calculate the number of chords that have been completed, and how much of the current chord has been completed. Calculating the position from that is easy when you know the previous and next hit positions. As these hit positions are at equal distances along the circle boundary, that is a matter of converting polar coordinates (an angle, and a distance of 1 radian) to Cartesian coordinates.
I will demonstrate this with JavaScript code. It will not be a great effort to wrap this in PHP:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var radius = canvas.height / 2 - 5;
var pixel = 1/radius;
// transform the canvas so that 0,0 is in the center of the canvas,
// and a unit circle would cover most of the height of the canvas:
context.setTransform(radius, 0, 0, radius, radius+2, radius+2);
// draw unit circle
context.beginPath();
context.arc(0, 0, 1, 0, 2 * Math.PI, false);
context.lineWidth = pixel;
context.strokeStyle = 'black';
context.stroke();
function drawPoint(point) {
// use a different color every 30 seconds:
context.fillStyle = Date.now() % 60000 > 30000 ? 'red' : 'blue';
context.fillRect(point.x-2*pixel, point.y-2*pixel, 4*pixel, 4*pixel);
}
function polarToCartesian(rad, dist) {
return {
x: Math.cos(rad) * dist,
y: Math.sin(rad) * dist
}
}
function pointBetween(a, b, fractionTravelled) {
return {
x: a.x + (b.x-a.x)*fractionTravelled,
y: a.y + (b.y-a.y)*fractionTravelled
}
}
// 4 parameters are needed:
var startRadians = 0; // distance along circle boundary from (0,1)
var hitAngle = Math.PI/2.931; // PI/2 would be head-on impact along diagonal
var speed = 0.4; // radians per second
var startTime = Date.now()/1000; // seconds
//
// Calculate some derived values which remain constant:
// - theta as used on https://en.wikipedia.org/wiki/Chord_%28geometry%29
// - chordSize formula comes from that wiki article.
var theta = 2 * hitAngle;
var chordSize = 2 * Math.sin(theta/2); // in radians
function drawCurrentPosition() {
// Note that this calculation does not look at the previous result,
// but uses the original parameters and time passed to calculate
// the objects current position.
var elapsedTime = Date.now()/1000 - startTime; // in secs
var distanceTravelled = speed * elapsedTime; // in radians
var chordsTravelled = distanceTravelled / chordSize; // in number of chords
var chordsTravelledComplete = Math.floor(chordsTravelled);
var fractionOnChord = chordsTravelled - chordsTravelledComplete; // 0<=f<1
var lastHitRadians = startRadians + chordsTravelledComplete * theta; // rad
var nextHitRadians = lastHitRadians + theta;
var lastHitPos = polarToCartesian(lastHitRadians, 1); // (x,y)
var nextHitPos = polarToCartesian(nextHitRadians, 1);
var currentPos = pointBetween(lastHitPos, nextHitPos, fractionOnChord);
drawPoint(currentPos);
}
// Demo: keep drawing the object's position every 0.1 second:
setInterval(drawCurrentPosition, 100);
<canvas id="myCanvas" width="200" height="200"></canvas>
Addendum: PHP code
Here is some code that could be useful for use in PHP. It uses the same calculations as the above JavaScript code, but does not keep running. Instead it first checks if there is a started game in the session scope, if not, it starts the "clock". At every request (reload of the page), the new position is calculated and printed on the page as an X,Y pair.
The coordinates are normalised, based on a unit circle (radius 1). The game parameters are hard-coded, but you could easily let them be passed via POST/GET parameters:
session_start(); // needed to persist game data for this user session
function getNewGame($startRadians, $hitAngle, $speed) {
$game = array();
$game["startTime"] = microtime(true);
$game["startRadians"] = $startRadians;
$game["theta"] = 2 * $hitAngle;
$game["chordSize"] = 2 * sin($hitAngle);
$game["speed"] = $speed;
return (object) $game;
}
function polarToCartesian($rad, $dist) {
return (object) array(
"x" => cos($rad) * $dist,
"y" => sin($rad) * $dist
);
}
function pointBetween($a, $b, $fractionTravelled) {
return (object) array(
"x" => $a->x + ($b->x-$a->x)*$fractionTravelled,
"y" => $a->y + ($b->y-$a->y)*$fractionTravelled
);
}
function getCurrentPosition($game) {
// Note that this calculation does not look at the previous result,
// but uses the original parameters and time passed to calculate
// the objects current position.
$elapsedTime = microtime(true) - $game->startTime; // in secs
$distanceTravelled = $game->speed * $elapsedTime; // in radians
$chordsTravelled = $distanceTravelled / $game->chordSize; //number of chords
$chordsTravelledComplete = floor($chordsTravelled);
$fractionOnChord = $chordsTravelled - $chordsTravelledComplete; // 0<=f<1
$lastHitRadians = $game->startRadians
+ $chordsTravelledComplete * $game->theta; // in radians on circle
$nextHitRadians = $lastHitRadians + $game->theta;
$lastHitPos = polarToCartesian($lastHitRadians, 1); // (x,y)
$nextHitPos = polarToCartesian($nextHitRadians, 1);
$currentPos = pointBetween($lastHitPos, $nextHitPos, $fractionOnChord);
return $currentPos;
}
// check if this is the first time the user loads this page:
if (!isset($_SESSION["game"])) {
// start game with some game parameters:
$_SESSION["game"] = getNewGame(0, pi()/2.931, 0.4);
}
// calculate the position based on game info and current time:
$pos = getCurrentPosition($_SESSION["game"]);
// print the result:
echo "Current position: {$pos->x}, {$pos->y}<br>";
I have seen examples of enabling certain dates, disabling certain dates, changing background colors...etc, but I was looking for suggestions on how to place a Red / or \ on a date based on a mysql return.
I have a 2 story house I rent out. Upper and Lower Level. If Upper is rented for a specific date I am looking for a red / to be placed on the date. If Lower Level is rented place a red \ on the date. If both are rented on the same date the end result would be a red X on the date.
unavailableDates would be where both upper and lower are rented out
upperavailableDates would be where only upper is rented out
loweravailableDates would be where only lower is rented out
suggestions would be greatly appreciated.
<input id="picker1">
var unavailableDates = ["27-11-2013", "28-11-2013", "29-11-2013"];
var upperavailableDates = ["01-12-2013", "02-12-2013", "03-12-2013"];
var loweravailableDates = ["24-12-2013", "25-12-2013", "26-12-2013"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(function() {
$("#picker1").datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: unavailable
});
});
I'm trying to calculate elapsed hours between two times. When calculating PM to AM it will give me a negative result so I need to add 12 hours to the negative number for correct elapsed time. For this I have to add the condition if ($some_result < 0). It works in php but not js, I can't figure out why
Demo: http://jsfiddle.net/wH7sC/1/
function calculateTime() { //gets time elapsed between 2 time marks
var valuestart = $("select[name='timestart']").val();
var valuestop = $("select[name='timestop']").val();
//create date format
var timeStart = new Date("01/01/2007 " + valuestart).getHours();
var timeEnd = new Date("01/01/2007 " + valuestop).getHours();
var hourDiff = timeEnd - timeStart;
if ( hourDiff < 0 ) { //this is not working
hourDiff += 12;
}
return hourDiff;
}
//prepare function on load
$(document).ready(function() {
$("select").change(calculateTime);
calculateTime();
});
//execute function when changing select options
$(function() {
$("select").change(function() {
$( "#result" ).val( calculateTime() );
});
});
It's not the if statement failing. You need you add 24, not 12:
http://jsfiddle.net/sparebyte/wH7sC/2/
I recommend installing Chrome, Firefox, or IE9, opening the javascript developer console and making use of the console.log(...) function. I don't recommend using IE9, its output leaves me wanting.
I had been given a requirement from client saying limit the textarea – 200 characters in English, it is approximate 66 Chinese characters for UTF8.
I wonder how do I check them whether it is chinese character or english character and calculating them in the sense of maximum length ?
Alright so I found a way (UTF-8 based) and somehow useful for me. But when I thought of client side, it was somehow still "yucks" ever since they are still able to edit it when inspect the dom element.....
Please advice me. Thanks
Code:
My textarea and count box:
<textarea class="message" name="quiz_answer" cols="30" rows="4"></textarea><br />
<span class="countdown"></span>
Jquery document ready:
updateCountdown();
$('.message').attr('maxLength','25');
$('.message').keyup(updateCountdown);
updateCountdown function():
var previous = '';
var current = '';
//Count textarea words
function updateCountdown() {
var countMe = $(".message").val();
if(previous==''){
previous = countMe;
current = countMe;
}else{
current = countMe;
}
var escapedStr = encodeURI(countMe);
if (escapedStr.indexOf("%") != -1) {
var count = escapedStr.split("%").length - 1;
if (count == 0) count++ //perverse case; can't happen with real UTF-8
var tmp = escapedStr.length - (count * 3);
count = count + tmp;
} else {
count = escapedStr.length;
}
// 200 is the max message length
var remaining = 200 - count;
$('.countdown').text(remaining + ' characters remaining.');
if(remaining < 0){
$(".message").val(previous);
}else{
previous = current;
}
}
I am having some problems with the way PHP and javascript round numbers. I am using PHP's round function and this javascript function:
function roundNumber(number, decimals) {
var newnumber = new Number(number+'').toFixed(parseInt(decimals));
var value = parseFloat(newnumber);
return value;
}
The number i am trying to round is 43.65 * 2.5 + 40% which when done using a calculator = 152.775 or when rounded in PHP = 152.78.
In javascript when i do a console.log the number is 152.774999999998 and when rounded with the above function gives me 152.77
Any help to reslove this issue is greatly appreciated
This isn't anything to do with rounding per se, but is to do with how decimal numbers are represented in binary-based hardware.
Check out the floating point guide for lots more information on this, as well as solutions/alternatives.
Please have a look at How to deal with floating point number precision in JavaScript?
Here is an example
function roundNumber(number, decimals) {
decimals = parseInt(decimals,10);
var dec = Math.pow(10,decimals)
console.log(dec,parseFloat(number)*dec);
number=""+Math.round(parseFloat(number)*dec+.0000000000001); // fixed the .X99999999999
return parseFloat(number.slice(0,-1*decimals) + "." + number.slice(-1*decimals))
}
var val = 43.65 * 2.5;
val+= val*0.40
console.log(val+' ~= 152.78? --> '+roundNumber(val,2).toFixed(2));
console.log('15.803 ~= 15.80? --> '+roundNumber(15.803,2).toFixed(2));
console.log('15.805 ~= 15.81? --> '+roundNumber(15.805,2).toFixed(2));
console.log('14.803 ~= 14.80? --> '+roundNumber(14.803,2).toFixed(2));
console.log('0.575 ~= 0.58? --> '+roundNumber(0.575,2).toFixed(2));
I was thinking a bit on this, and wanted to share my solution, let it not go to waste:
function roundNumber(number, decimals) {
var d = parseInt(decimals,10),
dx = Math.pow(10,d),
n = parseFloat(number),
f = Math.round(Math.round(n * dx * 10) / 10) / dx;
return f.toFixed(d);
}
This does not use string functions, or any forced up or down rounding.
Test it here: http://jsfiddle.net/inti/hMrsp/4/
Edit: corrected, was cutting down zeros at the end
php rounds to 152.78, because it sees 152.77499 which is 152.775 and in the end 152.178. can't you use rounded value from php?
It is because the different precisions used in JS (by the browser) and PHP or actually how many bits are used to store the numbers.
you can make your JS rounding function do this to round to the 2nd digit
Math.round(floatNumber*100)/100
Find below javascript function for number format
<script type="text/javascript">
function format_number(pnumber,decimals){
if (isNaN(pnumber)) { return 0};
if (pnumber=='') { return 0};
var snum = new String(pnumber);
var sec = snum.split('.');
var whole = parseFloat(sec[0]);
var result = '';
if(sec.length > 1){
var dec = new String(sec[1]);
dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
var dot = dec.indexOf('.');
if(dot == -1){
dec += '.';
dot = dec.indexOf('.');
}
while(dec.length <= dot + decimals) { dec += '0'; }
result = dec;
} else{
var dot;
var dec = new String(whole);
dec += '.';
dot = dec.indexOf('.');
while(dec.length <= dot + decimals) { dec += '0'; }
result = dec;
}
return result;
}
var value = format_number(newnumber,2);
</script>