Following on from my previous thread, I went on to design the following Objects.
/* --- LEAP Namespace --- */
var LEAP = {};
/* --- LEAP.Schedule Object --- */
LEAP.Schedule = function(){//init
this.weeks = [];
this.calculateWeeks();
};
LEAP.Schedule.prototype.pad = function (n) {
return n>9 ? n : "0"+n;
};
LEAP.Schedule.prototype.calculateWeeks = function(){
this.date = new Date ( 2011, 8, 5 ); // First week of new school year
this.num = 36; // Calendar number of this week
this.weeks.push(new LEAP.Schedule.week(this.date, this.num));
for (var i = 1; i < 51; i++) {
var week = i * 7;
var updated_date = new Date ();
updated_date.setDate(this.date.getDate() + week);
if (this.num > 51) {
this.num = 0;
}
this.num++;
this.weeks.push(new LEAP.Schedule.week(updated_date, this.num));
}
};
LEAP.Schedule.prototype.getWeeks = function(){
return this.weeks;
};
/* --- LEAP.Schedule.week Object --- */
LEAP.Schedule.week = function(n_date, n_week){
this.week = n_week;
this.date = n_date;
this.year = this.date.getFullYear();
var JSMonth = this.date.getMonth();
JSMonth += 1;
this.month = JSMonth;
this.day = this.date.getDate();
};
LEAP.Schedule.week.prototype.getJSDate = function(){
return this.date;
};
LEAP.Schedule.week.prototype.getStartDate = function(){
return this.year + "-" + LEAP.Schedule.pad(this.month) + "-" + LEAP.Schedule.pad(this.day);
};
LEAP.Schedule.week.prototype.getEndDate = function(){
var EndOfWeek = this.date;
EndOfWeek.setDate(this.date.getDate() + 6);
var year = EndOfWeek.getFullYear();
var month = LEAP.Schedule.pad(EndOfWeek.getMonth() + 1);
var day = LEAP.Schedule.pad(EndOfWeek.getDate());
return year + "-" + month + "-" + day;
};
LEAP.Schedule.week.prototype.getLabel = function(){
return "Week " + this.week + ": " + this.day + (this.day==1||this.day==21||this.day==31?"st":this.day==2||this.day==22?"nd":this.day==3||this.day==23?"rd":"th") + " " + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][this.month-1] + " " + this.year;
};
I'm now using a <SELECT> box to filter some other data, which works successfully, apart from the fact that every time the $('#filter').change() event is triggered, the dates are being incremented.
WeeklyUpdate.init = function() {
UWA.Data.getJson(WeeklyUpdate.URL + "?cmd=getPointTotals", WeeklyUpdate.getTotalPoints);
var Scheduleobject = new LEAP.Schedule();
var weeks = Scheduleobject.getWeeks();
WeeklyUpdate.displayWeekFilter(weeks);
}
WeeklyUpdate.displayWeekFilter = function(weeks) {
var WeekFilterDisplayHTML = '<select id="filter"><option>Click here</option><option value="all">- All, to date</option>';
var now = new Date();
for (var i = 0; i < weeks.length; i++) {
if (weeks[i].getJSDate() < now) {
var label = weeks[i].getLabel();
WeekFilterDisplayHTML += '<option value="' + i + '">' + label + '</option>';
}
}
WeekFilterDisplayHTML += '</select>';
$('div#filter').html(WeekFilterDisplayHTML);
//WeeklyUpdate.filterPointTotalsByStaff( $(this).val() )
$("select#filter").change( function() { WeeklyUpdate.filterPointTotalsByStaff( weeks, $(this).val() ) } );
}
WeeklyUpdate.filterPointTotalsByStaff = function(weeks, val) {
if (val >= 0 && val != "all") {
var StartDate = weeks[val].getStartDate();
var EndDate = weeks[val].getEndDate();
If I add alert(StartDate + ' // ' + EndDate); after those variables, I can see that the EndDate is being incremented every time, rather than being incremented once and then consistently returning the correct EndDate regardless of how many times it is selected from the SELECT box. The StartDate on the other hand works correctly every time.
What should happen is that this.date (which returns a JS date Object for the week being requested) should be the start of the week, then the getEndDate() function should increment that date by 6 days and return the correct date in a MySQL-compatible format. This shouldn't increment every time its <OPTION> is selected from the SELECT box; it should always return the same date.
I'm guessing that it's something to do with the way I've used EndOfWeek = this.date;, but I don't understand why or how.
Many thanks again.
Probably doesn't matter here but is bad form anyway:
for (i = 1; i < 51; i++) {
The variable i should be declared.
In the statement (my wrapping):
$("select#filter").change( function() {
WeeklyUpdate.filterPointTotalsByStaff( weeks, $(this).val() )
});
You do not show how weeks is initialised or assigned a value. There is a weeks property of LEAP.Schedule instances, but above it is used in the context of a global variable.
Related
I am trying to get the date string value(mm/dd/yyyy)from a custom date and time field and set the returned value back into the custom field. I found this script and modified it but it does not seem to work. When I step through the code it breaks on var year = startDate.getFullYear() + ""; Any ideas what I am doing wrong? Thanks.
function ConcatChainsAuth() {
var startDate = Xrm.Page.getAttribute("new_dateauthorized").getValue();
if (startDate != null) {
var year = startDate.getFullYear() + "";
var month = (startDate.getMonth() + 1) + "";
var day = startDate.getDate() + "";
var dateFormat = month + "-" + day + "-" + year;
Xrm.Page.getAttribute("new_dateauthorized").setValue(dateFormat);
}
var lookupObject = Xrm.Page.getAttribute("new_chain");
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
var Chain = lookUpObjectValue[0].name;
}
}
var lookupObject = Xrm.Page.getAttribute("new_package");
if (lookupObject != null) {
var lookUpObjectValue = lookupObject.getValue();
if ((lookUpObjectValue != null)) {
var Package = lookUpObjectValue[0].name;
}
}
var concatedField = Chain + "-" + Package + "-" + dateFormat;
Xrm.Page.getAttribute("new_name").setValue(concatedField);
Xrm.Page.data.entity.save();
}
Assuming that new_dateauthorized is a CRM date field, then Xrm.Page.getAttribute("new_dateauthorized").getValue() will return a Date object.
In which case you can just manipulate the Date object, like so:
var currentDate = Xrm.Page.getAttribute("new_dateauthorized").getValue();
currentDate.setMonth(currentDate.getMonth() + 1);
Xrm.Page.getAttribute("new_dateauthorized").setValue(currentDate);
However, adding months in this fashion fails in some cases, check out the comments here for more info.
I have a time/date converter. When the user enters "130" for example it returns "06/07/2016 01:30:00" when they enter "6 7 16" for example it returns "06/07/2016 00:00:00" but when the user enters "6 7 16 130" for example it returns "06/07/2016 false:00"
Here is my relevant code (can show more if need be):
function checkDateTime(val) {
var nowDate = new Date();
var month, day, year, time;
var ar;
if (eval(val)) {
var tval = val.value;
ar = tval.split(' ');
if (ar.length === 3) { // i.e. if it's supposed to be a date
ar[0] = month;
ar[1] = day;
ar[2] = year;
document.getElementById("FromDate").value = CheckDate(val) + ' ' + '00:00:00';
//checkDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]);
}
//alert(LeftPadZero(ar[0]) + ' ' + LeftPadZero(ar[1]) + ' ' + LeftPadZero(ar[2]));
//alert(CheckDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]));
if (ar.length === 1) { // if it's a time
ar[0] = time;
var MM = nowDate.getMonth() + 1;
var DD = nowDate.getDate();
var Y = nowDate.getFullYear();
var nowDateFormat = LeftPadZero(MM) + '/' + LeftPadZero(DD) + '/' + Y;
alert(ar[0]);
document.getElementById("FromDate").value = nowDateFormat + ' ' + checktime(val) + ':00';
}
if (ar.length === 4) { // if date and time
ar[0] = month;
// alert(ar[0]);
ar[1] = day;
// alert(ar[1]);
ar[2] = year;
// alert(ar[2]);
ar[3] = time;
// alert(ar[3]);
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
// alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
}
}
}
function CheckDate(theobj) {
var isInvalid = 0;
var themonth, theday, theyear;
var arr;
if (eval(theobj)) {
var thevalue = theobj.value;
arr = thevalue.split(" ");
if (arr.length < 2) {
arr = thevalue.split("/");
if (arr.length < 2) {
arr = thevalue.split("-");
if (arr.length < 2) {
isInvalid = 1;
}
}
}
if (isInvalid == 0) {
themonth = arr[0];
theday = arr[1];
if (arr.length == 3) {
theyear = arr[2];
} else {
theyear = new Date().getFullYear();
}
if (isNaN(themonth)) {
themonth = themonth.toUpperCase();
//month name abbreviation array
var montharr = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
for (i = 0; i < montharr.length; i++) {
//if the first 3 characters of month name matches
if (themonth.substring(0, 3) == montharr[i]) {
themonth = i + 1;
break;
}
}
} else {
if (themonth < 1 || themonth > 12) {
isInvalid = 1;
}
}
}
if (isNaN(themonth) || isNaN(theday) || isNaN(theyear)) {
isInvalid = 1;
}
if (isInvalid == 0) {
var thedate = LeftPadZero(themonth) + "/" + LeftPadZero(theday) + "/" + LeftPadZero(theyear);
return thedate;
} else {
return false;
}
}
}
function checktime(x) {
var tempchar = new String;
tempchar = MakeNum(x);
if (tempchar != '' && tempchar.length < 4) {
//e.g., if they enter '030' make it '0030'
if (tempchar.length == 3) {
tempchar='0' + tempchar;
}
//e.g, if they enter '11' make it '1100'
if (tempchar.length == 2) {
tempchar=tempchar + '00';
}
//e.g, if they enter '6' make it '0600'
if (tempchar.length == 1) {
tempchar='0' + tempchar + '00';
}
}
if (tempchar==null || tempchar == '') {
return false;
}
else {
if (tempchar=='2400') {
return false;
}else{
var tempnum= new Number(tempchar);
var swmin = new Number(tempnum % 100);
var swhour = new Number((tempnum-swmin)/100);
if (swhour < 25 && swmin < 60) {
x = LeftPadZero(swhour) + ":" + LeftPadZero(swmin);
return x;
}
else {
return false;
}
}
}
return false;
/*
if(eval(changecount)!=null){
changecount+=1;
}
*/
}
function MakeNum(x) {
var tstring = new String(x.value);
var tempchar = new String;
var f = 0;
for (var i = 0; i < tstring.length; i++) {
// walk through the string and remove all non-digits
chr = tstring.charAt(i);
if (isNaN(chr)) {
f=f;
}
else {
tempchar += chr;
f++;
}
}
return tempchar;
}
I have tried numerous things to figure out why the time element returns false in an array of length 4, but not an array length 1 for some reason, including setting various alerts and checking the console. I have googled this problem several times and came up empty.
To reiterate, my problem is that the time element returns false in an array of 4, and what I am trying to accomplish is for the user to input a date and time and have them both formatted and displayed correctly.
Can anybody help and/or offer any advice and/or suggestions? Thanks!
Edit: user enters '130' should convert to '06/07/2016(today's date) 01:30:00'
6 7 16 should convert to '06/07/2016 00:00:00'
6 7 16 130 should convert to '06/07/2016 01:30:00'
There seems to be some missing parts here... various functions and whatever input type these ones need are excluded from your post... However, taking a guess, I'm going to say that when you are making your final "checktime" call, rather than passing the full "val" variable, you should just be passing the last chunk of your split input, "ar[3]" in this case. That way, only that piece is evaluated by the function.
IE:
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
should be
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(ar[3]) + ':00';
Again, this is just a guess due to the missing pieces.
Edit:
After getting some additional details, the issue DOES seem to be in the data being sent to the checktime function, however, due to the current code setup, the fix is actually just making sure that the data being processed by the checktime function is only the last item in the array... see below for the correction within the checktime function:
tempchar = MakeNum(x);
becomes
tempchar = MakeNum(x).split(' ').pop();
I am working on a small piece of code that looks to see if a value is equal to 'December 25 - January 9' and if it does increment the year (that I append to it) by one
However I can not figure out how to find that value. Every time I run the script it skips to the else part of the script when that value is selected.
Any guidance is appreciated
if ($('#date').val === 'December 25 - January 9') {
var startDates = $('#date').val().split(" - ");
var year = $('year').val;
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
}
else{
var startDates = $('#date').val().split(" - ");
var year = $('#year').val() ;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
console.log(myStartDates);
console.log(myEndDates);
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
Problem is you are using JQuery but chexking value as in javascript
$('#date')[0].value === 'December 25 - January 9'
or
$('#date').val() === 'December 25 - January 9'
should do it.
I see two places where you used val instead of val(), you want to call the function val not access a non-existent val field
if ($('#date').val() === 'December 25 - January 9') { // <-- val()
var startDates = $('#date').val().split(" - ");
var year = $('year').val(); // <-- val()
Try this. It should work.
You have var should be var() also year should be #year
if ($('#date').val() === 'December 25 - January 9') {
var startDates = $('#date').val().split(" - ");
var year = $('#year').val();
var yearDec = parseInt(year, 10) + 1;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + yearDec;
var startDate = Date.parse(payPdStart);
console.log(startDates);
console.log(year);
console.log(yearDec);
console.log(payPdStart);
console.log(payPdEnd);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + "</td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
}
else{
var startDates = $('#date').val().split(" - ");
var year = $('#year').val() ;
var payPdStart = startDates[0] + ' ' + year;
var payPdEnd = startDates[1] + ' ' + year;
var startDate = Date.parse(payPdStart);
myStartDates = new Date(startDate);
var endDate = Date.parse(payPdEnd);
myEndDates = new Date(endDate)
console.log(myStartDates);
console.log(myEndDates);
while (myStartDates <= myEndDates) {
var firstCol = "<td style='border:none;'>" + myStartDates + " </td>";
$('#timeTable').append("<tr>" + firstCol + "</td>");
var newDate = myStartDates.setDate(myStartDates.getDate() + 1);
start = new Date(newDate);
}
I'm using a JQuery/PHP script which displays 12 clocks on a page. The Javascript file calls a PHP file to determine the timezone offset, but with 12 clocks to display, 12 PHP requests is crashing my page.
JS FILE
/*these are the div id names you added to your html*/
var clockAllDivs = [
"clock0",
"clockNYC",
"clockTOR",
"clockVAN",
"clockLAX",
"clockFRNK",
"clockSAO",
"clockTOK",
"clockBEI",
"clockHON",
"clockLONDON",
"clockPARIS",
"clockSYDNEY"
];
var tz = jstz.determine(); // Determines the time zone of the browser client
tz.name();
/*get timezone from this list: http://php.net/manual/en/timezones.php*/
var timeZones = [
tz.name(),
"America/New_York",
"America/Toronto",
"America/Vancouver",
"America/Vancouver",
"Europe/Zurich",
"America/Sao_Paulo",
"Asia/Tokyo",
"Asia/Hong_Kong",
"Asia/Hong_Kong",
"Europe/London",
"Europe/Paris",
"Australia/Sydney"
];
/*titles you want to show for each clock*/
var clockTitles = [
tz.name(),
"Los Angeles",
"Melbourne",
"Kathmandu",
"Tokyo",
"Johannesburg"
];
var useTitle1 = false;
var useTitle2 = false;
var clockWidthHeight = 118;//width and height of the clock
var distanceBetweenClockTitle = 5;
var secondHandSpeed = 100;//in ms, the lower the number, the faster
var smoothRotation = false;//true or false
var useSecondHand = false;//set to false if you don't want to see the 2nd hand
/*location of the images*/
var clockFaceImg = "img/clockBg.png";
var hourHandImg = "images/hourHand.png";
var minuteHandImg = "images/minuteHand.png";
var secondHandImg = "images/secondHand.png";
var amImg = "images/am.png";
var pmImg = "images/pm.png";
/*location of the high res images for retina display*/
var clockFaceHighResImg = "img/clockBgHighRes.png";
var hourHandHighResImg = "images/hourHandHighRes.png";
var minuteHandHighResImg = "images/minuteHandHighRes.png";
var secondHandHighResImg = "images/secondHandHighRes.png";
var amHighResImg = "images/amHighRes.png";
var pmHighResImg = "images/pmHighRes.png";
/*text for days and months*/
var dayText = [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
];
var monthText = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
];
///////////////////////////////
//Do not edit below this line//
///////////////////////////////
var clockDivs = [];
var offsets = [];
var minuteHand;
var hourHand;
var secondHands = [];
var minuteHands = [];
var hourHands = [];
var ams = [];
var pms = [];
var retina = false;
var imgsLoaded = 0;
var imagesToLoad = 6;
var callInterval = 1000;
var thisOffset;
var formerHr = [];
var isStart = true;
var tzChecked = 0;
//once the page is ready . . .
$( document ).ready(function() {
var dNow = new Date();
thisOffset = dNow.getTimezoneOffset();//figure out user's timezone
//get the timezone info for each of your clocks
for(var i = 0;i<clockAllDivs.length;i++){
getTZOutput(i);
}
});
//build each clock
function AnalogClock(){
retina = window.devicePixelRatio > 1;//check if retina
//if it's high res, use the high res images
if(retina){
clockFaceImg = clockFaceHighResImg;
hourHandImg = hourHandHighResImg;
minuteHandImg = minuteHandHighResImg;
secondHandImg = secondHandHighResImg;
amImg = amHighResImg;
pmImg = pmHighResImg;
}
//determine if you want to use the second hand
if(useSecondHand == false){
imagesToLoad = imagesToLoad - 1;
}
//change the call interval for smooth rotation
if(smoothRotation == true && useSecondHand){
callInterval = 50;
}
//create each clock visually
for(var i = 0;i<clockAllDivs.length;i++){
var clockAllDiv = $("#" + clockAllDivs[i]);
//add bg
clockAllDiv.append("<div id='analog-clock" + i + "' class='myClock'></div>")
//add title
if(useTitle1 || useTitle2){
var clockTitlePos = distanceBetweenClockTitle + clockWidthHeight;
if(useTitle1)clockAllDiv.append("<div><p class='clockTitle'>" + clockTitles[i] + "</p></div>");
if(useTitle2){
clockAllDiv.append("<div><p id='title2_" + i + "' class='clockTitle2'></p></div>");
}
$('.clockTitle').css({"margin-top":clockTitlePos + 'px'});
if(useTitle2 && !useTitle1)$('.clockTitle2').css({"margin-top":clockTitlePos + 'px'});
}
clockDivs[i] = "analog-clock" + i;
var clockDiv = $("#" + clockDivs[i]);
//set clock holder css
clockDiv.css({"height":clockWidthHeight + "px", "width":clockWidthHeight + "px", "position":"relative"});
//add more graphical elements
clockDiv.append("<img id='bg' src=" + clockFaceImg + " height="+clockWidthHeight+" width="+clockWidthHeight+" />");
//add the div for am/pm
clockDiv.append("<img id='am' class='ampm' src='" + amImg + "' width='28' height='18' />");
clockDiv.append("<img id='pm' class='ampm' src='" + pmImg + "' width='28' height='18' />");
//add hands
$("<img id='hourHand' src=" + hourHandImg + " />").appendTo("#" + clockDivs[i]);
clockDiv.append("<img id='minuteHand' src=" + minuteHandImg + " />");
if(useSecondHand)clockDiv.append("<img id='secondHand' src=" + secondHandImg + " />");
//define elements
if(useSecondHand)secondHands[i] = $("#" + clockDivs[i] + " #secondHand");
minuteHands[i] = $("#" + clockDivs[i] + " #minuteHand");
hourHands[i] = $("#" + clockDivs[i] + " #hourHand");
ams[i] = $("#" + clockDivs[i] + " #am");
pms[i] = $("#" + clockDivs[i] + " #pm");
if(i == 0){
//check to see if the images are loaded
$('#bg').load(function() { checkIfImagesLoaded(); });
if(useSecondHand)secondHands[i].load(function() { checkIfImagesLoaded(); });
minuteHands[i].load(function() { checkIfImagesLoaded(); });
hourHands[i].load(function() { checkIfImagesLoaded(); });
ams[i].load(function() { checkIfImagesLoaded(); });
pms[i].load(function() { checkIfImagesLoaded(); });
}
//set clock css
var handIds = $("#" + clockDivs[i] + " #bg, #hourHand, #minuteHand, #secondHand");
handIds.css({"position":"absolute"});
}
};
function checkIfImagesLoaded(){
//this gets called each time an image is loaded
imgsLoaded++;
if(imgsLoaded == imagesToLoad){//once all the images are loaded
for(var i = 0;i<clockAllDivs.length;i++){
//adjust widths and heights if 2x resolution
if(retina){
if(useSecondHand)secondHands[i].css( { "height":secondHands[i].height()/2, "width":secondHands[i].width()/2 } );
minuteHands[i].css( { "height":minuteHands[i].height()/2, "width":minuteHands[i].width()/2 } );
hourHands[i].css( { "height":hourHands[i].height()/2, "width":hourHands[i].width()/2 } );
}
//set the position of the hands
if(useSecondHand)secondHands[i].css( { "left": (clockWidthHeight - secondHands[i].width())/2 + "px", "top": (clockWidthHeight - secondHands[i].height())/2 + "px" });//set x and y pos
minuteHands[i].css( { "left": (clockWidthHeight - minuteHands[i].width())/2 + "px", "top": (clockWidthHeight - minuteHands[i].height())/2 + "px" });//set x and y pos
hourHands[i].css( { "left": (clockWidthHeight - hourHands[i].width())/2 + "px", "top": (clockWidthHeight - hourHands[i].height())/2 + "px" });//set x and y pos
//if(useSecondHand)setSecondStart();
//fade the clocks in
$("#" + clockAllDivs[i]).animate({ opacity:1 }, "slow");
}
//call rotatehands function
setInterval(function(){
rotateHands();
}, callInterval);//1000 = 1 second
if(!smoothRotation)rotateHands();//make sure they start in the right position
}
}
function rotateHands(){
for(var i = 0;i<clockAllDivs.length;i++){
//get current time/date from local computer
var now = new Date();
now.setMinutes(now.getMinutes() + offsets[i] + thisOffset);
//set the second hand
var secondAngle = 6 * now.getSeconds();//turn the time into angle
if(smoothRotation)var smoothSecondAngle = now.getMilliseconds()/1000 * 6 + secondAngle;
var currentHr = now.getHours();
if(formerHr[i] && currentHr != formerHr[i]){
getTZOutput(i);
setDayMonthTxt(now, i);
}
formerHr[i] = currentHr;
if(useSecondHand){
if(smoothRotation){
secondHands[i].rotate(smoothSecondAngle, 'abs');//set the hand angle
}else{
if(secondAngle == 0){
secondHands[i].rotate(-6, 'abs');//set the hand angle
}
secondHands[i].rotate({ animateTo:secondAngle, duration:secondHandSpeed}, 'abs');
}
}
//set the minute hand
var minuteAngle = 6 * now.getMinutes() + secondAngle/60;//turn the time into angle
minuteHands[i].rotate(minuteAngle, 'abs');//set the hand angle
//set the hour hand
var hourAngle = 360/12 * currentHr;//turn the time into angle
var hourAngleWOffset = hourAngle + minuteAngle/12;
hourHands[i].rotate(hourAngleWOffset%360, 'abs');//set the hand angle
}
isStart = false;
}
//get timezone info from the
function getTZOutput(thisNum) {
$.ajax({
type: "POST",
url:'timezone-clock-scripts/getTimezoneTime.php',
data: {thisTz:timeZones[thisNum]},
dataType: "json",
success: function (response) {
offsets[thisNum] = response/60;
allTZChecked();
},
error: function (){
console.log("error");
}
});
}
//make sure the php script has called first
function allTZChecked(){
tzChecked++;
if(tzChecked == clockAllDivs.length){
AnalogClock();
for(var i = 0;i<clockAllDivs.length;i++){
var now = new Date();
now.setMinutes(now.getMinutes() + offsets[i] + thisOffset);
setDayMonthTxt(now, i);
}
}
}
function setDayMonthTxt(now, thisNum){
var thisDay = dayText[now.getDay()];
var thisMonth = monthText[now.getMonth()];
var thisDate = now.getDate();
var thisYear = now.getFullYear();
//this is what the actual strong of text looks like, but you can modify it as you please.
if(useTitle2)$("#title2_" + thisNum ).html(thisDay + " " + thisMonth + " " + thisDate + ", " + thisYear);
//determine am/pm
if(now.getHours() < 12){
ams[thisNum].fadeIn();
pms[thisNum].fadeOut();
}else{
ams[thisNum].fadeOut();
pms[thisNum].fadeIn();
}
}
PHP FILE
<?php
$tzTxt = $_REQUEST['thisTz'];
$date = new DateTime();
$tz = new DateTimeZone($tzTxt);
$date->setTimezone($tz);
echo $date->format(Z);
//echo $date;
?>
Sometimes the page will reload, other times I get a a "Connection Was Reset" error.
When I disable this script, everything works fine.
Is there a way to alter my PHP settings to allow this script to work, or should I explore another option?
If the problem is that your server cannot handle the simultaneous requests, there are a few options:
Only call your php script once and send the information of all clocks at once. You can have your script return a json object that contains all offsets. This is what I would do.
Call the function when the previous version has finished (in the callback or have it return a promise). Possible, but overly complicated and you will hit your server still with an extra request for each clock.
How can I modify this script to encase the AM/PM text in a div?
I already tried modifying the areas where it outputs the ampm with a div, but it didnt put the element in a div, instead displaying the and tags as plaintext.
function myTime() {
var dst = 0; // set to 1 for daylight savings time
// update this as you go on and off daylight saving time
var loc = ''; // set to your location
var mtz = -5; // set to your local timezone (hours ahead of UTC, negative if behind)
var stdz = ''; // standard time indicator
var dayz = ''; // daylight saving time indicator (blank if you dont have daylight saving)
var showDate = 0; // 0 = don't show, 1 = international format, 2 = US format
// do not alter anything below this line
var newP = document.createElement("div"); var txt = '' + loc + ' '; var newT = document.createTextNode(txt); newP.appendChild(newT); var newP2 = document.createElement("div"); newP2.id = 'time'; var txt2 = setDsp(mtz,dst,stdz,dayz,showDate); var newT2 = document.createTextNode(txt2); newP2.appendChild(newT2); var frag = document.createDocumentFragment(); frag.appendChild(newP); frag.appendChild(newP2); var d2 = document.getElementById('datetime'); d2.parentNode.replaceChild(frag,d2);
setTimeout('updDsp('+mtz+',' +dst+',"' +stdz+'","' +dayz+'","'+showDate+'")', 5000);}
var pageLoaded = 0; window.onload = function() {pageLoaded = 1;}
function loaded(i,f) {if (document.getElementById && document.getElementById(i) != null) f(); else if (!pageLoaded) setTimeout('loaded(\''+i+'\','+f+')',100);
}
function updDsp(mtz,dst,stdz,dayz,showDate) {var obj = document.getElementById('time'); obj.firstChild.data = setDsp(mtz,dst,stdz,dayz,showDate); setTimeout('updDsp('+mtz+ ','+dst+ ',"'+stdz+ '","'+dayz+ '","'+showDate+'")', 5000);}
function setDsp(mtz,dst,stdz,dayz,showDate) {var dayname = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday','Friday', 'Saturday']; var month = ['January','February','March','April','May','June','July','August','September','October','November','December']; var now = new Date; now.setUTCMinutes(now.getUTCMinutes() + (mtz + dst)*60); var dow = now.getUTCDay(); var minute = now.getUTCMinutes();
var hour = now.getUTCHours(); if (hour > 11) {ampm = 'PM'; hour -= 12;} else {ampm = 'AM'} if (hour == 0) {hour = 12;} if (minute < 10) {pad = ':0';} else {pad = ':';} var txt = hour + pad + minute + ' ' + '' + ampm + ''; if (dst) txt += dayz; else txt += stdz; txt += ' '
if (showDate == 1) txt += ' ' + now.getUTCDate() + ' ' + month[now.getUTCMonth()] + ', ' + now.getUTCFullYear();
if (showDate == 2) txt += ' ' + month[now.getUTCMonth()] +' ' + now.getUTCDate() + ', ' + now.getUTCFullYear();
return (txt);
}
loaded('datetime',myTime);
Your code is way over complex. I'd suggest replacing the myTime() function with this that just builds HTML rather than create all the various text nodes. This also puts the AM or PM designation in a <span class="ampm"> so it can be styled appropriately:
function myTime() {
var dst = 0; // set to 1 for daylight savings time
// update this as you go on and off daylight saving time
var loc = ''; // set to your location
var mtz = -5; // set to your local timezone (hours ahead of UTC, negative if behind)
var stdz = ''; // standard time indicator
var dayz = ''; // daylight saving time indicator (blank if you dont have daylight saving)
var showDate = 0; // 0 = don't show, 1 = international format, 2 = US format
var timeStr = setDsp(mtz, dst, stdz, dayz, showDate);
timeStr = timeStr.replace(/AM|PM/i, '<span class="ampm">$&</span>');
var d = document.getElementById('datetime');
d.innerHTML = '<div id="time">' + loc + " " + timeStr + '</div>';
setTimeout(myTime, 500);
}
And here's a working version: http://jsfiddle.net/jfriend00/jTbf2/