Modify Script to Include DIV around AM/PM - javascript

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/

Related

Hour is not showing in 00 format

I have this code:
<span id="live_time">Server Time: <strong><?php echo date('h:i:s A'); ?></strong></span>
<script type="text/javascript">
// use php to get the server time
var serverdate = new Date('<?php echo date('F d, Y h:i:s'); ?>');
function refresh_time(){
serverdate.setSeconds(serverdate.getSeconds() + 1);
var hh=serverdate.getHours();
var m=serverdate.getMinutes();
var s=serverdate.getSeconds();
m=checkTime(m);
s=checkTime(s);
var dd = " AM";
var h = hh;
if (h >= 12) {
h = hh-12;
dd = " PM";
}
if (h == 0) {
h = 12;
}
var output = h+":"+m+":"+s+""+dd;
document.getElementById("live_time").innerHTML = 'Server Time: <strong>'+output+'</strong>';
}
function checkTime(i) {
if (i < 10) {i = "0" + i};
return i;
}
window.onload = function(){
setInterval("refresh_time()", 1000);
}
</script>
When I access page first time it show me 07:11:14 AM after one second time become 7:11:15 AM How I can output at every refresh in H format? like 07:11:15 ?
just add the 0 manually:
var date = new Date();
currentHours = date.getHours();
var currentHours2 = 6;
var currentHours3 = 18;
currentHours = ("0" + currentHours).slice(-2);
currentHours2 = ("0" + currentHours2).slice(-2);
currentHours3 = ("0" + currentHours3).slice(-2);
console.log(currentHours)
console.log(currentHours2)
console.log(currentHours3)
You can use ES8 padStart() to pad the hour with 0.
var h = "5";
console.log(h.padStart(2, "0"));
Or if not use the older syntax
var h = "5";
console.log(h.length == 1 ? "0"+h : h);

Javascript clear array was working but suddenly it's not

Iam working in cordova with cordova-local-notifications plugin. First the clear function was working but now when I clear and restart the application the notification all show up...
This is my clear function:
$('.clearbtn').click(function(){
var arraylength = info.data;
arraylength.splice(0,arraylength.length);
console.log('clear',arraylength);
});
The console log shows me that the array has nothing inside it. And this is the outcome of the console.log(info.data)
and this is the all reminder page:
$(document).on("pagebeforeshow","#all",function(){
var html = '';
for(var count = 0; count < info.data.length; count++){
console.log(info.data);
var time = new Date(info.data[count][3]);
var addHour = time.setHours(time.getHours());
var date = new Date(addHour);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2);
var imgPath = 'img/icons/alert.png';
html = html + "<tr><td class='img-table'><img src=" + imgPath + "></td>" + "<td><span class='time-aside'><strong>" + formattedTime + "</strong></span><h4>" + info.data[count][1] + "</h4><p>" + info.data[count][2] + "</p></td></tr>";
}
$('.clearbtn').click(function(){
var arraylength = info.data;
arraylength.splice(0,arraylength.length);
console.log('clear',arraylength);
});
$("table#notificationTable tbody").empty();
$("table#notificationTable tbody").append(html).closest("table#notificationTable").table("refresh").trigger("create");
});
I really don't get it because it was working before but I don't know why its not anymore!
I had to clear localStorage aswell.. Because I push it to localstorage as string. Here is a rewrite of the function:
$('.clearbtn').click(function(){
var arraylength = info.data;
arraylength = 0;
localStorage.clear();
});

Javascript if / else not working properly [Time Formatting AM/PM]

I am trying to have a div show the current time but it always shows it in military time, so I went to use an if / else statement to help but it doesn't seem to work.
Javascript
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
if(time.getHours() > 12) {
timeHourFix = time.getHours() - 12 + "PM";
}else {
timeHourFix = time.getHours() + "AM";
};
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
it should display the time like 5:35 PM but it still shows 17:35
That's because your are declaring the variable formatted before the timeHourFix is actually modified. Try the code below.
var time = new Date(Date.now());
var hour = time.getHours();
var t_hour = hour > 12 ? (hour - 12) : ((hour == 0) ? hour + 12 : hour);
var formatted = t_hour + " : " + time.getMinutes() + (hour > 11 ? " PM" : " AM");
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id=hourmin>
The time is not being formatted because the variable formatted is being set before timeHourFix or timeHour is being set. I think it's easiest to set formatted in the if else statement directly:
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeMinute = time.getMinutes();
var formatted;
if(time.getHours() > 12) {
formatted = time.getHours() - 12 + ":" + timeMinute + " PM";
} else {
formatted = time.getHours() + ":" + timeMinute + " AM";
};
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
In your case the problem was you were modifying the variable timeHourFix after it was appended to the string, there is no live linking between the string and the timeHourFix variable so any changes you make to the variable after the string concatenation will not be reflected in the original value.
Also there are multiple other issues like the AM/PM should be at the end of the string so that also have to be changed. Also there are other issues with timeHourFix like how the value 0030 will be handled, it should be shown as 12:30 AM not 00:30 AM
var time = new Date(Date.now());
var timeHour = time.getHours();
//set the hour part
var timeHourFix = timeHour > 12 ? timeHour - 12 : timeHour == 0 ? 12 : timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
//set the AM/PM at the end of the string
formatted += timeHour >= 12 ? ' PM' : ' AM';
$(document).ready(function() {
$('#hourmin').text(formatted)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="hourmin"></div>
Because you set formatted before setting the right values to timeHourFix. Move the assignment of formatted to below the else block.
You could always do something like this if you want to simplify your code.
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
$(document).ready(function() {
var timeofday = "";
if(timeHour > 12) {
timeHourFix = timeHour - 12;
timeofday = "PM";
}else {
timeHourFix = timeHour;
timeofday = "AM";
};
var formatted = timeHourFix + ":" + timeMinute + " " + timeofday;
$('#hourmin').text(formatted)
});
This is perfectly working full code.
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
if(time.getHours() > 12) {
time = time.getHours() - 12 + " : " + timeMinute + " PM";
}
else {
time = time.getHours() +" : " + timeMinute + " AM";
};
$( document ).ready(function() {
$('#hourmin').text(time)
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<p id="hourmin">Time Display</p>
</body>
</html>

Google Apps Script: "Missing ';' before statement"

Today is my first day using Google Apps Script. I am trying to make a script to grab weather information from the Wunderground Api and paste it into a spreadsheet.
For some reason I am getting the error message "Missing ';' before statement. (Line 34)".
I've searched for a solution but cant find why I am getting this error in my code.
//Everyday this script gets weather data from Weather Underground and records it in this spreadsheet.
cDay = 0, cTemp = 1, cHumidity = 2, cPressure=3, cSparkline=4, cConditions=5;
nCols=7;
function getTemp() {
var url = 'http://api.wunderground.com/api/' + appKey + '/conditions/q/CO/Aspen.json';
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var response = UrlFetchApp.fetch(url);
var contentText = response.getContentText();
var conditions = Utilities.jsonParse(contentText);
var todaysConditions = conditions;
var temp = todaysConditions.current_observation.temp_c;
var humidity = todaysConditions.current_observation.relative_humidity;
var pressure = todaysConditions.current_observation.pressure_in;
var conditions = todaysConditions.response.features.conditions;
sheet.insertRowAfter(1);
var range = sheet.getRange(2,1,1, nCols);
var row = range.getValues()[0];
var d = new Date;
var month = d.getMonth() + 1;
var day = d.getDate();
var year = d.getFullYear();
var hour = d.getHours() + 1;
var minutes = d.getMinutes();
row[cDay] = month + '/' + day + '/' + year + '' + hour + ':' minutes; //here is the error
row[cTemp] = temp;
row[cHumidity] = humidity;
row[cPressure] = pressure;
row[cConditions] = conditions;
var nRows = numRows >= 10 ? 10 : numRows;
//row[cSparkline] = "=SPARKLINE(R[0]C[-3]:R[" + (nRows-1) + "]C[-3])";
range.setValues([row]);
}
Any help is appreciated
You have missed the '+' sign
row[cDay] = month + '/' + day + '/' + year + '' + hour + ':' + minutes;

get javascript to write to variable rather than document.write

I have the following javascript that prints the timestamp:
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(hours + "" + minutes + seconds + month + "" + day + "" + year)
//-->
</script>
However I want to use this timestamp in many places in the page, how can i call it like $timestamp so i can control where its placed?
Thanks in advance.
Set a variable, like:
var timestamp = hours + "" + minutes + seconds + month + "" + day + "" + year;
and later in code use that variable to show info in your page, like:
var container = document.getElementById('container1');
container.innerHTML = timestamp;
where 'container1' is a html element like span, div, p, etc. ex:
<span id="container1"></span>
answer
<script>
function startTime()
{
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<span id="txt"></span>
<script type="text/javascript">
startTime().swap('txt');
</script>

Categories