Javascript Date Function Not working - javascript

Hi I am trying to add 31 days to 'myDate' which is the current date. It is supposed to get the date add 31 days, then the convertDate function is supposed to translate it to something like 'Nov 31, 2012'. But it doesn't work. Does anyone know why?
Here is the primary function...
function process (infoarray) {
var myDate = new Date();
//var final = convertDate(myDate);
var length = infoarray.length;
var final_string;
for (var b = 0; b < length; b++) {
if (b == 0) {
if (infoarray[b][3] == 'After') {
final_string = '<b>' + infoarray[b][3] + ' ' + infoarray[b][1] + '</b><br/>' + infoarray[b][0] + '<br/>';
} else {
final_string = '<b>' + infoarray[b][1] + ' ' + infoarray[b][3] + ' ' + infoarray[b][2] + '</b><br/>' + infoarray[b][0] + '<br/>';
}
} else {
if (infoarray[b][3] == 'After') {
final_string = final_string + '<br/><b>' + infoarray[b][3] + ' ' + convertDate(myDate.setDate(myDate.getDate() + 31)) + '</b><br/>' + infoarray[b][0] + '<br/>';
} else {
final_string = final_string + '<br/><b>' + infoarray[b][1] + ' ' + infoarray[b][3] + ' ' + infoarray[b][2] + '</b><br/>' + infoarray[b][0] + '<br/>';
}
}
}
return final_string;
}
Here is the line i am focused on from the function above...
final_string = final_string + '<br/><b>' + infoarray[b][3] + ' ' + convertDate(myDate.setDate(myDate.getDate() + 31)) + '</b><br/>' + infoarray[b][0] + '<br/>';
Here is the convertDate function...
function convertDate(d) {
var day = d.getDate();
if (day < 10) {
day = '0' + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct', 'Nov','Dec'];
var currentMonth = months[month];
return (currentMonth + ' ' + day + ', ' + year);
}

myDate.setDate(...) modifies the value of the Date instance, but doesn't return anything.
You need to call setDate first, then pass the variable to your function.

Here.
First calculate then call
DEMO;
var myDate = new Date();
myDate.setDate(myDate.getDate()+31);
final_string = final_string + '<br/><b>' +
infoarray[b][3] + ' ' +
convertDate(myDate) + '</b><br/>' + infoarray[b][0] + '<br/>';
Or add it to the function:
.... convertDate(myDate,31) + ....
With
function convertDate(d,offset) {
if ( offset ) d.setDate(d.getDate()+offset);
var day = d.getDate();
if (day < 10) {
day = '0' + day;
}
var year = d.getFullYear();
var month = d.getMonth();
var months=['Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct', 'Nov','Dec'];
var currentMonth = months[month];
return (currentMonth + ' ' + day + ', ' + year);
}
DEMO

By using setDate, you tell the Date object to set the day number to something between 32 and 62, which doesn't make much sense.
A good way to add 31 days would be to use getTime, which returns the number of mseconds ellapsed since 1st Jan 1970:
myDate.setTime( myDate.getTime()+31*24*60*60*1000 );
//31Days x 24 hours x 60 minutes x 60 seconds x 1000 msecs

Related

Value is not displayed though condition in JavaScript is true

Below is my code which displays latest B'day and anniversary wishes (assuming event is on same day or 15 days old).
In below code, Jac's b'day is on 3rd of October still its name is displayed.
Alert alert((datediff(parseDate(dates[1]), (today)) <= 15) && (datediff(parseDate(dates[1]), (today)) >= 1)); displays value is true. Still name is not displayed.
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var y = today.getFullYear();
var dates = ["10/15/" + y, "10/3/" + y, "10/15/" + y, "9/6/" + y, "10/10/" + y, "10/1/" + y]; // MM/DD format
var names = ["Mac", "Jac", "Tom", "Abhay", "Mahesh", "Jayesh"];
var joingDates = ["10/16/" + y, "09/20/" + y, "10/2/" + y, "9/6/" + y, "10/10/" + y, "10/3/" + y];
var joiningyears = ["2000","2002","2010","2011","2011","2014"];
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
//alert((datediff(parseDate(dates[1]), (today)) <= 15) && (datediff(parseDate(dates[1]), (today)) >= 1));
for(var i = 0; i < dates.length; i++) {
//document.getElementById("mySup").innerHTML = getGetOrdinal(dates[i].split('/')[0]);
if ((datediff(parseDate(dates[i]), (today)) <= 15) && (datediff(parseDate(dates[i]), (today)) >= 1))
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very" + " Happy Birthday to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
"!!! (" +
getGetOrdinal(dates[i].split('/')[1]).split('')[0] +
getGetOrdinal(dates[i].split('/')[1]).split('')[1] +
getGetOrdinal(dates[i].split('/')[1]).split('')[2].sup() +
getGetOrdinal(dates[i].split('/')[1]).split('')[3].sup() +
" " +
months[dates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
for(var i = 0; i < joingDates.length; i++) {
if (datediff(parseDate(joingDates[i]), (today)) <= 15 && datediff(parseDate(joingDates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very " +
"Happy ".bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[0].bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[1].sup().bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[2].sup().bold().fontcolor("blue") +
" Work Anniversary to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
" with " +
"Siemens".fontcolor("green").bold() +
"!!! (" +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[0] +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[1] +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[2].sup() +
getGetOrdinal(dates[i].split('/')[1]).split('')[3].sup() +
" " +
months[joingDates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
<p id="demo"><p>
With enclosing text into "<sup>" and "</sup>", it worked. Thank you all for suggestions.
function parseDate(str) {
var mdy = str.split('/');
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
// Take the difference between the dates and divide by milliseconds per day.
// Round to nearest whole number to deal with DST.
function datediff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var y = today.getFullYear();
var dates = ["10/15/" + y, "10/03/" + y, "10/15/" + y, "09/06/" + y, "10/10/" + y, "10/01/" + y]; // MM/DD format
var names = ["Mac", "Jac", "Tom", "Abhay", "Mahesh", "Jayesh"];
var joingDates = ["10/16/" + y, "09/20/" + y, "10/02/" + y, "09/06/" + y, "10/10/" + y, "10/04/" + y];
var joiningyears = ["2000","2002","2010","2011","2011","2014"];
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
for(var i = 0; i < dates.length; i++) {
//document.getElementById("mySup").innerHTML = getGetOrdinal(dates[i].split('/')[0]);
if ((datediff(parseDate(dates[i]), (today)) <= 15) && (datediff(parseDate(dates[i]), (today)) >= 1))
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very" + " Happy Birthday to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
"!!! (" +
getGetOrdinal(dates[i].split('/')[1]).split('')[0] +
getGetOrdinal(dates[i].split('/')[1]).split('')[1] +
"<sup>" +
getGetOrdinal(dates[i].split('/')[1]).split('')[2] +
getGetOrdinal(dates[i].split('/')[1]).split('')[3] +
"</sup> " +
" " +
months[dates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
for(var i = 0; i < joingDates.length; i++) {
if (datediff(parseDate(joingDates[i]), (today)) <= 15 && datediff(parseDate(joingDates[i]), (today)) >= 1)
{
document.getElementById("demo").innerHTML = document.getElementById("demo").innerHTML +
"<li>" +
"Wishing a very " +
"Happy ".bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[0].bold().fontcolor("blue") +
"<sup>" +
getGetOrdinal(y-joiningyears[i]).split('')[1].bold().fontcolor("blue") +
getGetOrdinal(y-joiningyears[i]).split('')[2].bold().fontcolor("blue") +
"</sup> " +
" Work Anniversary to ".bold().fontcolor("blue") +
names[i].bold().fontcolor("Red") +
" with " +
"Siemens".fontcolor("green").bold() +
"!!! (" +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[0] +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[1] +
"<sup>" +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[2] +
getGetOrdinal(joingDates[i].split('/')[1]).split('')[3] +
"</sup> " +
months[joingDates[0].split('/')[0]-1] +
")" +
"<br>";
}
}
function getGetOrdinal(n) {
var s=["th","st","nd","rd"],
v=n%100;
return n+(s[(v-20)%10]||s[v]||s[0]);
}
<p id="demo"><p>

JS dropdown 14 days in future [duplicate]

This question already has answers here:
How to get next seven days from X and format in JS
(6 answers)
next 7 days in drop-down list [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to create a dropdown list that shows 14 days in the future via JS.
Right now it is showing only 7 days but with duplicates.
What is wrong?
screenshot dropdown
function createDates() {
$("#DT").find('option').remove().end().append('<option value="" selected>~#SELECT_DT~</option>');
var counter = 0;
var index = 1;
console.log(holidays);
while (counter < 14) {
var date = new Date();
date.setDate(date.getDate() + index);
var day = date.getDay();
var month = date.getMonth() + 1;
var isWeekend = (day == 6) || (day == 0);
var checkTime1 = getTimeOfDate(date.getFullYear(), month, date.getDate());
var isFound = false;
var selected = "";
if (index == ~(IF(#DT<>'',#DT,0))~) {
selected = 'selected="selected"';
}
if (!isWeekend) {
if (holidays.length > 0) {
$.each(holidays, function(key, obj) {
var hDay = new Date(obj.DT);
var checkTime2 = getTimeOfDate(hDay.getFullYear(), hDay.getMonth() + 1, hDay.getDate());
if (checkTime1 == checkTime2) {
isFound = true;
}
});
} else {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
if (!isFound) {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
}
index++;
}
}
The second if block should come under the first, also set isFound to false in the beginning:
if (!isWeekend) {
isFound = false;
if (holidays.length > 0) {
$.each(holidays, function(key, obj) {
var hDay = new Date(obj.DT);
var checkTime2 = getTimeOfDate(hDay.getFullYear(), hDay.getMonth() + 1, hDay.getDate());
if (checkTime1 == checkTime2) {
isFound = true;
}
});
if (!isFound) {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
} else {
$("#DT").append('<option value="' + index + '"' + selected + '>' + getDayString(day) + ' ' + date.getDate() + ' ' + getMonthString(month) + ' ' + date.getFullYear() + '</option>');
counter++;
}
}

Yahoo finance xchange - taking the last update time

I'm doing a query on Yahoo finance xchange, but seems the time of update is not the most updated. Seems random, for each refresh, this value change, sometimes most updated, and sometimes less updated.
There is a way to always get the last time it was updated ?
Thank you.
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDUSD%22%2C%22USDEUR%22%2C%20%22USDJPY%22%2C%20%22USDCNY%22%2C%20%22USDGBP%22%2C%20%22USDBRL%22%2C%20%22EUREUR%22%20%2C%22EURUSD%22%2C%20%22EURJPY%22%2C%20%22EURCNY%22%2C%20%22EURGBP%22%2C%20%22EURBRL%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=", function (data) {
var indices = '<p style=\"border:1px solid #ccc; width:auto; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[0].Name + '</strong> ' + money(data.query.results.rate[0].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[1].Name + '</strong> (Fechamento ' + money(data.query.results.rate[1].Rate) + ') - ' + data.query.results.rate[1].Date + ' - ' + data.query.results.rate[1].Time + '</p>' +
'<p><strong>' + data.query.results.rate[2].Name + '</strong> (Fechamento ' + money(data.query.results.rate[2].Rate) + ') - ' + data.query.results.rate[2].Date + ' - ' + data.query.results.rate[2].Time + '</p>' +
'<p><strong>' + data.query.results.rate[3].Name + '</strong> (Fechamento ' + money(data.query.results.rate[3].Rate) + ') - ' + data.query.results.rate[3].Date + ' - ' + data.query.results.rate[3].Time + '</p>' +
'<p><strong>' + data.query.results.rate[4].Name + '</strong> (Fechamento ' + money(data.query.results.rate[4].Rate) + ') - ' + data.query.results.rate[4].Date + ' - ' + data.query.results.rate[4].Time + '</p>' +
'<p><strong>' + data.query.results.rate[5].Name + '</strong> (Fechamento ' + money(data.query.results.rate[5].Rate) + ') - ' + data.query.results.rate[5].Date + ' - ' + data.query.results.rate[5].Time + '</p>' +
'<p style=\"border:1px solid #ccc; width:auto; margin:20px 0 0; padding:0 10px; background:#ddd;\"><strong>' + data.query.results.rate[6].Name + '</strong> ' + money(data.query.results.rate[6].Rate) + '</p>' +
'<p><strong>' + data.query.results.rate[8].Name + '</strong> (Fechamento ' + money(data.query.results.rate[8].Rate) + ') - ' + data.query.results.rate[8].Date + ' - ' + data.query.results.rate[8].Time + '</p>' +
'<p><strong>' + data.query.results.rate[7].Name + '</strong> (Fechamento ' + money(data.query.results.rate[7].Rate) + ') - ' + data.query.results.rate[7].Date + ' - ' + data.query.results.rate[7].Time + '</p>' +
'<p><strong>' + data.query.results.rate[9].Name + '</strong> (Fechamento ' + money(data.query.results.rate[9].Rate) + ') - ' + data.query.results.rate[9].Date + ' - ' + data.query.results.rate[9].Time + '</p>' +
'<p><strong>' + data.query.results.rate[10].Name + '</strong> (Fechamento ' + money(data.query.results.rate[10].Rate) + ') - ' + data.query.results.rate[10].Date + ' - ' + data.query.results.rate[10].Time + '</p>' +
'<p><strong>' + data.query.results.rate[11].Name + '</strong> (Fechamento ' + money(data.query.results.rate[11].Rate) + ') - ' + data.query.results.rate[11].Date + ' - ' + data.query.results.rate[11].Time + '</p>';
$('#info').html(indices);
});
money = function (n) {
var
c = 4,
d = ',',
t = '.',
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
Well, I ended up constructing a date for each element in the array (map) and then filtering them to the oldest date (reduce)
what do you want to do with this date, I am not sure but here it is...
UPDATED
updated to return full JSON record containing the latest date/time stamp (instead of returning only the latest date)
// sample response
var response = {"query":{"count":12,"created":"2016-04-29T20:13:39Z","lang":"en-us","results":{"rate":[{"id":"USDUSD","Name":"USD/USD","Rate":"1.0000","Date":"N/A","Time":"N/A","Ask":"1.0000","Bid":"1.0000"},
{"id":"USDEUR","Name":"USD/EUR","Rate":"0.8775","Date":"4/29/2016", "Time":"12:38pm","Ask":"0.8777","Bid":"0.8775"},{"id":"USDJPY","Name":"USD/JPY","Rate":"107.3910","Date":"4/29/2016","Time": "2:55pm","Ask":"107.3940","Bid":"107.3910"},{"id":"USDCNY","Name":"USD/CNY","Rate":"6.4868","Date":"4/29/2016","Time":"12:49pm","Ask":"6.4878","Bid":"6.4868"},{"id":"USDGBP","Name":"USD/GBP","Rate":"0.6843","Date":"4/29/2016","Time":"1:15pm","Ask":"0.6844","Bid":"0.6843"},{"id":"USDBRL","Name":"USD/BRL","Rate":"3.4492","Date":"4/29/2016","Time":"3:33pm","Ask":"3.4496","Bid":"3.4492"},{"id":"EUREUR","Name":"EUR/EUR","Rate":"1.0000","Date":"1/29/2016","Time":"8:26am","Ask":"1.0002","Bid":"0.9998"},{"id":"EURUSD","Name":"EUR/USD","Rate":"1.1443","Date":"4/29/2016","Time":"3:08pm","Ask":"1.1443","Bid":"1.1443"},{"id":"EURJPY","Name":"EUR/JPY","Rate":"122.5650","Date":"4/29/2016","Time":"4:00pm","Ask":"122.6200","Bid":"122.5100"},{"id":"EURCNY","Name":"EUR/CNY","Rate":"7.4054","Date":"4/29/2016","Time":"2:08pm","Ask":"7.4070","Bid":"7.4037"},{"id":"EURGBP","Name":"EUR/GBP","Rate":"0.7836","Date":"4/29/2016","Time":"3:22pm","Ask":"0.7837","Bid":"0.7836"},{"id":"EURBRL","Name":"EUR/BRL","Rate":"3.9637","Date":"4/29/2016","Time":"4:28pm","Ask":"3.9679","Bid":"3.9595"}]}}};
//console.log(response.query.results.rate);
var times = response.query.results.rate.map(function(elem){
if( elem.Time === 'N/A' || elem.Time === 0){
elem.fullDateTimeStamp = elem.Time;
//console.log(elem);
return elem;
}
// create full date from the time (using time and date combined)
// 1) is it AM or PM
var elemIsPm = (elem.Time.substring(elem.Time.length-2).indexOf("am") == -1);
// 2) remove AM/PM and get hour:min into array
var elemArr = elem.Time.substring(0, elem.Time.length-2).split(":");
// 3) add 12 hours if PM and not noon
if( elemIsPm && elemArr[0] != 12){
elemArr[0] = parseInt(elemArr[0]) + 12;
}
//console.log(elemArr[0]);
// 4) however, if it is 12, we deduct 12 if it's not PM
if( elemArr[0] == 12 && !elemIsPm ){
elemArr[0] = elemArr[0] - 12;
}
// 5) create date object
var elemDateString = elem.Date;
var elemDateOnly = new Date(elemDateString);
//console.log(elemDateOnly);
var elemTS = new Date(elemDateOnly.getFullYear(), elemDateOnly.getMonth(), elemDateOnly.getDate(), elemArr[0], elemArr[1], 0, 0);
elem.fullDateTimeStamp = elemTS;
// console.log(elem);
// 4) return
return elem;
});
console.log( times );
var lastOne = times.reduce(function(prevVal, elem) {
// console.log('p');
// console.log(prevVal );
// console.log('e');
// console.log(elem );
if( prevVal === 'N/A' || prevVal === 0 || prevVal.Time){
return elem;
}
//console.log(prevVal.fullDateTimeStamp);
return (prevVal.fullDateTimeStamp < elem.fullDateTimeStamp)? elem : prevVal;
}, 0);
document.getElementById('latest').innerHTML = JSON.stringify(lastOne);
console.log('====> ');
console.log( JSON.stringify(lastOne.fullDateTimeStamp) );
Last date:
<div id='latest'></div>

how to get current time in razor view using javascript

I have tried many ways mentioned below but none of them is working
var currentTime = Date.parse(date + ' ' + currentDate.getHours() + ':' + currentDate.getMinutes() + ':' + currentDate.getSeconds());
var t = DateTime.Now.ToString("h:mm:ss tt")
DateTime.Now.TimeOfDay etc
thanks in advance
try using this function..
function $dateTime() {
var d = new Date();
var dd = d.getDate();
var mm = d.getMonth()+1;//January is 0!
var yyyy = d.getFullYear();
var h=d.getHours();
var m=d.getMinutes();
var s=d.getSeconds();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
if(h<10){h='0'+h}
if(m<10){m='0'+m}
if(s<10){s='0'+s}
return yyyy + '-' + mm + '-' + dd + ' ' + h + ':' + m + ':' + s;
}
returns the value 2015-01-06 and current time..

setInterval not working with specific function

I have a script that creates a bar at the top right of the browser with current date and time. I'm trying to update it every thirty seconds so that it keeps a live time, and not just the time when the page loaded. You'll see that I create the time bar with the set_time() function onload, and then create a setInterval that is intended to call timer() which in turn updates the time by calling the set_time() function again. The timer is clearly firing because every 4 seconds I get an alert box with "hi" (from the timer() function), but then when it's supposed to call set_time() after this it isn't working. I should be getting an alert with "set time" (located at the end of the set_time() function) each time the timer is fired as well, which I do not. Can anybody help?
window.onload = function(){
set_time();
window.setInterval(timer, 4000);
};
function timer(){
alert('hi');
set_time();
}
function set_time(){
//create date object to manipulate
var d = new Date();
//current day of the week
var d_names= new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
curr_day = d.getDay();
//current date
var m_names = new Array("January", "February", "March",
"April", "May", "June", "July", "August", "September",
"October", "November", "December");
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
//current Time
var a_p = "";
var curr_hour = d.getHours();
if (curr_hour < 12)
{
a_p = "a.m.";
}
else
{
a_p = "p.m.";
}
if (curr_hour == 0)
{
curr_hour = 12;
}
if (curr_hour > 12)
{
curr_hour = curr_hour - 12;
}
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
{
curr_min = "0" + curr_min;
}
element = document.getElementById('dateTime');
if(element){
//if dateDiv already exists, update contents
dateDiv.innerHTML = '';
dateDiv.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ', ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
}
else{
//else create new dateDiv and append it to DOM body
var dateDiv = document.createElement('div');
dateDiv.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ', ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
dateDiv.id = 'dateTime';
document.body.appendChild(dateDiv);
}
alert('set time');
//setTimeout("set_time()", 3000);
}
You are assigning the #dateTime div to the element variable and even check for it's existance, but when you have confirmed that element exists you use a dateDiv variable. That one is undefined and throws an exception on setting its innerHTML property; you should be able to see that in your browser's error console.
Use this code instead:
var element = document.getElementById('dateTime');
if (!element) {
element = document.createElement('div');
document.body.appendChild(element);
}
element.innerHTML = '<p>' + d_names[curr_day] + ', ' + m_names[curr_month] + ' ' + curr_date + ', ' + curr_year + ' | ' + '<strong>' + curr_hour + ':' + curr_min + ' ' + a_p + '</strong>' + '</p>';
If you look at your error console, you will see that javascript throws a 'dateDiv not defined' error here (just before the else):
dateDiv.innerHTML = '';
To avoid that (and get your script working), do this:
Code the div layer into your HTML (don't create it using javascript) like so:
<div id="dateTime"></div>
Remove the else block at the end (it is now superfluous because of step 1)
Add this to the top of set_time():
var dateDiv = document.getElementById( 'dateTime' );

Categories

Resources