Javascript toggling time type - javascript

So recently, for fun and to learn more about Javascript since I haven't ever done much web development, I've been making a site which will function as a clock which picks a color by making a color hex code from the time. Fairly basic, but I'm having a bit of an issue with a feature I want to implement.
A feature I'd like to have is to use a button on the webpage to toggle between UTC and local time. To accomplish this, I have the button (onclick) multiply a number by -1, to have a positive and negative representing each state. I have verified through console.log that the value itself is changed, but there is no visible change in the time being displayed.
So, I'd appreciate it if someone could take a look. Perhaps I'm misunderstanding how the code itself flows, or repeats.
Thanks! I can put up the HTML if need be, but I think only the JS will be necessary.
var h, m, s;
window.onload = function startTime() {
var today = new Date();
var buttonHasBeenPressed = -1; // -1 = false
document.getElementById("utcbtn").onclick = function() {
buttonHasBeenPressed = buttonHasBeenPressed * -1; // reverses value
console.log(buttonHasBeenPressed);
}
if (buttonHasBeenPressed == 1) {
getUTCTime(today);
} else {
getNormalTime(today);
}
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
var timeString = "" + h + ":" + m + ":" + s;
var colorString = "#" + h + m + s;
document.getElementById("main").innerHTML = timeString;
document.getElementById("hexcolor").innerHTML = colorString;
document.body.style.backgroundColor = colorString;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function getUTCTime(today) {
h = today.getUTCHours();
m = today.getUTCMinutes();
s = today.getUTCSeconds();
}
function getNormalTime(today) {
h = today.getHours();
m = today.getMinutes();
s = today.getSeconds();
}
Like I said as far as javascript I'm pretty much a novice, so this code probably isn't all that great - suggestions to improve it are always welcome!

The reason your code is not changing from UTC to normal time, is because you are setting a timeout for var t = setTimeout(startTime, 500);. In startTime you are immediately setting it to -1 var buttonHasBeenPressed = -1; // -1 = false. So each time it runs you set it back to -1. If you move the var buttonHasBeenPressed = -1; // -1 = false outside of the startTime function it will work. See updated code.
var h, m, s;
var buttonHasBeenPressed = -1; // -1 = false
window.onload = function startTime() {
var today = new Date();
document.getElementById("utcbtn").onclick = function() {
buttonHasBeenPressed = buttonHasBeenPressed * -1; // reverses value
console.log(buttonHasBeenPressed);
}
if (buttonHasBeenPressed == 1) {
getUTCTime(today);
} else {
getNormalTime(today);
}
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
var timeString = "" + h + ":" + m + ":" + s;
var colorString = "#" + h + m + s;
document.getElementById("main").innerHTML = timeString;
document.getElementById("hexcolor").innerHTML = colorString;
document.body.style.backgroundColor = colorString;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
function getUTCTime(today) {
h = today.getUTCHours();
m = today.getUTCMinutes();
s = today.getUTCSeconds();
}
function getNormalTime(today) {
h = today.getHours();
m = today.getMinutes();
s = today.getSeconds();
}
Edit:
I would also make buttonHasBeenPressed a boolean and setup a init() function where you add the onclick handler and start startTime so you are not adding the onclick handler each time.
var h, m, s;
var buttonHasBeenPressed = false;
window.onload = init;
function init() {
document.getElementById("utcbtn").onclick = function() {
buttonHasBeenPressed = !buttonHasBeenPressed;
console.log(buttonHasBeenPressed);
}
startTime();
}
function startTime() {
var today = new Date();
if (buttonHasBeenPressed) {
getUTCTime(today);
} else {
getNormalTime(today);
}
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
var timeString = "" + h + ":" + m + ":" + s;
var colorString = "#" + h + m + s;
document.getElementById("main").innerHTML = timeString;
document.getElementById("hexcolor").innerHTML = colorString;
document.body.style.backgroundColor = colorString;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
function getUTCTime(today) {
h = today.getUTCHours();
m = today.getUTCMinutes();
s = today.getUTCSeconds();
}
function getNormalTime(today) {
h = today.getHours();
m = today.getMinutes();
s = today.getSeconds();
}

buttonHasBeenPressed and setTimeout should not have been local to the startTime function.
Here's a working JSFiddle.

Related

Showing complete 24hr time display (00:00:00)

I have a basic script to display PST time based on 24:00hr UTC clock. Everything is working fine except it only displays 0:00:00 (h:m:s) for hours 0-9am and I want to have an extra 0 as a prefix (ex: 00:00:00).
My script is:
function startTime() {
const today = new Date();
let h = today.getUTCHours()-8;
let m = today.getUTCMinutes();
let s = today.getUTCSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
I tried adding the following with no such luck:
function checkTime(h) {
if (h < 10) {h = "0" + h}; // add zero in front of numbers < 10
return h;
}
Note that the en-GB locale displays half-past midnight as 00:30:00, but the en-US locale displays it as 24:30:00.
const today = new Date();
const time = today.toLocaleTimeString('en-GB',
{timeZone: 'America/Los_Angeles', hour12: false})
console.log(time)
Maybe you forgot to call h = checkTime(h);
function startTime() {
const today = new Date();
let h = today.getUTCHours()-8;
let m = today.getUTCMinutes();
let s = today.getUTCSeconds();
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
function checkTime(h) {
if (h < 10) {h = "0" + h}; // add zero in front of numbers < 10
return h;
}
startTime();
<div id="txt"></div>

Clock not working I need help, it's not working

I followed a tutorial on YT on how to put a clock, I've copied the exact code (well not exactly because of the "id") mine seems to be not working. this is my code
const hourEl = document.getElementsById ("hour");
const minuteEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");
const ampmEl = document.getElementById("ampm");
function updateClock (){
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
let ampm = "AM";
if(h> 12) {
h = h - 12;
ampm= "PM";
}
h = h > 10 ? "0" + h: h;
m = m > 10 ? "0" + m: m;
s = s > 10 ? "0" + s: s;
hourEl.innerText = h;
minuteEl.innerText = m;
secondsEl.innerText = s;
ampmEl, (innerText= ampm);
setTimeout(()=>{
}, 1000)
}
updateClock();
Mostly you just need to call the function from your timeout, but then you need to flip your > to < in your comparison, and fix a few typos (document.getElementsById, for example, should be document.getElementById):
const hourEl = document.getElementById ("hour");
const minuteEl = document.getElementById("minutes");
const secondsEl = document.getElementById("seconds");
const ampmEl = document.getElementById("ampm");
function updateClock (){
let h = new Date().getHours();
let m = new Date().getMinutes();
let s = new Date().getSeconds();
let ampm = "AM";
if(h> 12) {
h = h - 12;
ampm= "PM";
}
h = h < 10 ? "0" + h: h;
m = m < 10 ? "0" + m: m;
s = s < 10 ? "0" + s: s;
hourEl.innerText = h;
minuteEl.innerText = m;
secondsEl.innerText = s;
ampmEl, (innerText= ampm);
setTimeout(()=>{
updateClock()
}, 1000)
}
updateClock();
div {
display: inline-block;
}
<div id="hour"></div>:
<div id="minutes"></div>:
<div id="seconds"></div>
<div id="ampm"></div>

How to fix the error with my live chat function time

/* Navbar ClockDate */
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
h = checkTime(h);
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
}; // add zero in front of numbers < 10
return i;
}
I use this code for my clock in my live chat, but why does it return the wrong time? Specifically 4 hours earlier.

Cumbersome time parsing in JavaScript

I need a function to convert time in text from a format with day-part letters to digits.
E.g. 4:15PM -> 16:15, 4:15AM -> 4:15AM. Currently I have the following solution
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] (AM|PM)';
var reg = new RegExp(find, 'g');
pos = 0;
var result;
var formatedText = "";
while((result = reg.exec(text)) !== null) {
if(result[2] == "PM"){
var hours= parseInt(result[0], 10);
hours = hours + 12;
var hoursStr = hours.toString();
var newTime = hoursStr + result[0].substring(result[1].length,result[0].length - 3);
formatedText += newTime;
pos = reg.lastIndex;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
pos = reg.lastIndex;
}
}
if(pos < text.length){
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
I makes nicely cases like
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
But I strugle to make it process
console.log(formatTime("Some Text (11:00 AM - 1:00 PM)"));
This works for your examples.
I've added \\s? to the regex and made a minor change in the logic of cutting time (-2 instead of -3). Also I've moved variables definition to the beginning of the function to reflect hoisting in JavaScript.
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\\s?(AM|PM)';
var reg = new RegExp(find, 'g');
var pos = 0;
var formatedText = "";
var result, hours, hoursStr, newTime;
while ((result = reg.exec(text)) !== null) {
if (result[2] === "PM") {
hours= parseInt(result[0], 10);
hours = hours + 12;
hoursStr = hours.toString();
newTime = hoursStr + result[0].substring(result[1].length, result[0].length - 2);
formatedText += newTime;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
}
pos = reg.lastIndex;
}
if (pos < text.length) {
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
Here's an easier way to do this: Just use two functions. One to convert the hours, and another to match against PM times along with the replace() function.
Easy does it...
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return hours + ':' + minutes;
}
function formatTime(i_string) {
console.log(i_string.replace(/([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(PM)/gi, function newDate(x) {
return convertTime12to24(x.replace("PM", " PM"))
}));
}
formatTime("The time is now 4:15PM");
formatTime("The time is now 12:15PM");
formatTime("The time is now 4:00AM");
formatTime("The time is now 12:00AM");
formatTime("The time is now 11:00PM");

how to create a javascript countdown which on refreshing continues counting

I try it with javascript and jquery but no idea how to do that. i wont to let the timer not begins on refreshing counting again. It´s same as an auction when he counting down 3,2 and on refreshing he don´t begins again it should continue count down where it last ended. And on other products it must count from 3 again. Have anyboy an idea?
Edit: because some users missunderstood what i am searching for.
my issue is that i don´t know how to save the time when someone refresh the page to continue to count it down. if someone refresh the site at 21sec and he or she have 30 secs to make there choice. and after refreshing the site, the counter will count at 21sec down and not started again by 30sec again.
no ajax.
When possible hardcoded.
And if not possible then the cookie variant.
You can set a name to your window on load of the page. Before setting the name check whether this window already has a name.
if it doesn't have a name, set a name to the window and start counting at 0 and save the count value in a cookie each time it increment.
if it does have a name(that means page is reloaded), read the count value from the cookie and do the increment and save to cookie.
EDIT: Example, Call initCount() function on body load. Use decrementAndSave function to decrement the value of the count and save it to cookie.
var count = 3;// 3 -> 2 -> 1
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function initCount() {
if (window.name) {
count = getCookie("count_" + window.name);// to keep separate count cookies for each window
} else {
window.name = "w_" + (new Date().getTime());
count = 3;
setCookie("count_" + window.name, count, null);
}
}
function decrementAndSave() {
count--;
// separate cookie for each window or tab
setCookie("count_" + window.name, count, null);
}
It's not Perfect but I designed this script to do a 30min countdown and then to change some text during the last few seconds. The only issue with it is that when it gets to 1:00 it starts at 30:60 and I haven't figured out how to fix that yet. This may not work perfectly for what your looking for but it might put you on the right path.
<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
If you have a countdown, then you must have some sort of end time defined. So instead of having a countdown and just subtracting 1 every second, try something like this:
var endTime = new Date(2011,11,13,0,0,0); // Midnight of December 13th 2011
var timer = setInterval(function() {
var now = new Date();
var timeleft = Math.max(0,Math.floor((endTime.getTime()-now.getTime())/1000));
var d, h, m, s;
s = timeleft % 60;
timeleft = Math.floor(timeleft/60);
m = timeleft % 60;
timeleft = Math.floor(timeleft/60);
h = timeleft % 24;
timeleft = Math.floor(timeleft/24);
d = timeleft;
document.getElementById('counter').innerHTML = "Time left: "+d+" days, "+h+" hours, "+m+" minutes, "+s+" seconds.";
if( timeleft == 0) clearInterval(timer);
},1000);
var interval = 90000; //90 secounds
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("tooltip").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);

Categories