javascript if negative condition not working - php

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.

Related

Realtime jQuery Digital Clock with Server Time

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

Place \ / on JQuery Datepicker based on PHP MYSQL Result

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

include external code

I have the below code to display date/time in my page. When I have the code written in my index.php it runs fine. when I try to call it with:
<script type="text/javascript" src="scripts/clock.js">
Is not working.
Do I have to change anything? Thank you.
var weekdaystxt=["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
function showLocalTime(container, servermode, offsetMinutes, displayversion){
if (!document.getElementById || !document.getElementById(container)) return
this.container=document.getElementById(container)
this.displayversion=displayversion
var servertimestring=(servermode=="server-php")? '<? print date("D, F jS Y H:i:s", time())?>' : (servermode=="server-ssi")? '<!--#config timefmt="%B %d, %Y %H:%M:%S"--><!--#echo var="DATE_LOCAL" -->' : '<%= Now() %>'
this.localtime=this.serverdate=new Date(servertimestring)
this.localtime.setTime(this.serverdate.getTime()+offsetMinutes*60*1000) //add user offset to server time
this.updateTime()
this.updateContainer()
}
showLocalTime.prototype.updateTime=function(){
var thisobj=this
this.localtime.setSeconds(this.localtime.getSeconds()+1)
setTimeout(function(){thisobj.updateTime()}, 1000) //update time every second
}
showLocalTime.prototype.updateContainer=function(){
var thisobj=this
if (this.displayversion=="long")
this.container.innerHTML='<? print date("D, F jS Y")?>'
else{
var hour=this.localtime.getHours()
var minutes=this.localtime.getMinutes()
var seconds=this.localtime.getSeconds()
var ampm=(hour>=12)? "PM" : "AM"
var dayofweek=weekdaystxt[this.localtime.getDay()]
this.container.innerHTML=formatField(hour, 1)+":"+formatField(minutes)+":"+formatField(seconds)+" (UTC +2)"
}
setTimeout(function(){thisobj.updateContainer()}, 1000) //update container every second
}
function formatField(num, isHour){
if (typeof isHour!="undefined"){ //if this is the hour field
var hour=(num>24)? num-24 : num
return (hour==0)? 24 : hour
}
return (num<=9)? "0"+num : num//if this is minute or sec field
}
I'm not a php expert but my it seems that since your clock.js is a javascript file and not a php file, the php code in there does not get interpreted (not sure if that's the right word).

Javascript VS PHP rounding

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>

Using beforeShowDay in JQuery UI Datepicker to close out days of the week

what I am trying to do is grey out some days of the week for a venue for when it is closed. Each venue might be closed on different days.
I can use the following code as a test to close out all Sundays:
$('#bookingDatepicker').datepicker({
minDate: 0,
maxDate: '+3M',
dateFormat: 'DD, d MM, yy',
altField: '#actualDate',
altFormat: 'yy-mm-dd',
beforeShowDay: closedDays
});
function closedDays(date) {
if (date.getDay() == 0){
return [false,"","Venue Closed"];
} else { return [true, ""];
}
}
However I might have to close out more than one day and they might not run next to each other. In my code from the database I can create a string, examples below, which show what days are open...
1,2,3,4,5,6,0 //I would want to show no days closed
2,3,4,5,6 //I would want to show Sunday (0) and Monday (1) closed
I am not sure what to do with this though to get the code above to work. I am using PHP to create the string so can manipulate it using that if need be.
EDIT
As is usual when you post a question you get a minor breakthrough! I have developed the code below, it works if I use the dummy data in it, however I need find a way of wrapping my string values in "". That is now causing me trouble, if I just use var cloDays = [2,3,4,5] it ceases to work
var cloDays = ["2","3","4","5"];
function closedDays(date){
var sDate = date.getDay().toString();
if ($.inArray(sDate, cloDays) == -1) return [false,"","Venue Closed"];
else return [true, ""];
}
this post didn't solve my problem but pointed me in the right direction.
This is what worked the way I wanted:
var unavailableDates = ["9-5-2011","10-5-2011"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false,"","Unavailable"];
}
}
$('#iDate').datepicker({ minDate: +1, beforeShowDay: unavailable });
This blocks all dates in the past including today and then blocks the dates specified in the unavailableDates array.
Managed to fix it by running my string through the code below, basically explodes it into a PHP array and then encodes it using JSON_Encode. Seems to work perfectly:
$cloDays = json_encode(explode(",", $cloDays));

Categories