Leading zero if number is lower than 10 - bug with number 0 - javascript

I'm creating some kind of JS clocks where real life minute == 1 clock's hour. But there is one bug, every number in minutes which is lower than 10 is rewritten to "0"+minute, so it looks like 01, 02 and etc. but there is a problem with number 0, it's output is 0, not 00 as I wanted, here is my code.
// time and date
var minute = 57;
var hour = 0;
function getTime(){
$("#time").html(hour+":"+minute);
};
function init(){
setInterval(function(){getTime();}, 1000);
setInterval(function(){
if (minute == 59){
hour=++hour;
minute=minute-59; // (\(\ Hoo hoo
} // ( . .) you found
else { // c(“)(“) a bunny :)
minute=++minute;
if (minute < 10){
minute="0"+minute;
}
}
}, 1000);
}
init();
Thanks for any help. :)

You are setting minute = 0 in if block, not else.
Just replace minute=minute-59 with minute = '00', because that's only one case when you'll enter that if (minute must be equal to 59 and then you're subtracting 59 from it, so it'll be always 0).

How about:
$("#time").html(hour+":"+("00"+minute).slice(-2));
and remove the concatenation where you're incrementing the minute

hour = hour.toString();
minute = minute.toString();
while (hour.length < 2) hour = "0" + hour;
while (minute.length < 2) minute = "0" + minute;

Related

Why does EST JavaScript Date sets 12:00:00AM to 0:00:00 AM?

my JavaScript display time function works fine, but once it hits 12:00:00 AM EST, it changes to 0:00:00 AM. Essentially, I want it to show as 12:00:00 AM when the clock strikes midnight. I have included my code below so anyone can help? Thank you!
let session = document.getElementById("session");
if (session) {
displayTime();
setInterval(displayTime, 1000);
clearInterval(displayTime);
}
function displayTime() {
let dateTime = new Date();
let hrs = dateTime.getHours();
let mins = dateTime.getMinutes();
let sec = dateTime.getSeconds();
if (hrs > 12) {
session.innerHTML = "\xa0" + "PM";
} else {
session.innerHTML = "\xa0" + "AM";
}
if (hrs > 12) {
hrs = hrs - 12;
}
if (mins < 10) {
mins = "0" + mins;
}
if (sec < 10) {
sec = "0" + sec;
}
document.getElementById("hours").innerHTML = hrs;
document.getElementById("minutes").innerHTML = mins;
document.getElementById("seconds").innerHTML = sec;
}
There are two things to change.
The condition to display "PM" should be >= 12 instead of > 12
The mapping of 24-hours to 12-hours should never leave 0 as-is. You can use the remainder operator.
Here are the corrected relevant lines:
if (hrs >= 12) {
session.innerHTML = "\xa0" + "PM";
} else {
session.innerHTML = "\xa0" + "AM";
}
hrs = (hrs + 11) % 12 + 1;
Alternative
To format a time, look at toLocaleTimeString with its options:
dateTime.toLocaleTimeString("en-US")
If you really need to chop the date parts into different elements on your HTML document, then:
function displayTime() {
let dateTime = new Date();
let [hrs, mins, sec, apm] = dateTime.toLocaleTimeString("en-US").split(/\W/);
console.log(hrs, mins, sec, apm);
document.getElementById("hours").textContent = hrs;
document.getElementById("minutes").textContent = mins;
document.getElementById("seconds").textContent = sec;
document.getElementById("session").textContent = "\xa0" + apm;
}
Remarks
Unrelated, but clearInterval is called at the wrong time and with the wrong argument, which luckily makes it ineffective, or your timer wouldn't tick at all.
clearInterval should get as argument a value that was returned by a previous call to setInterval.
In your code clearInterval is executed immediately after setInterval, which makes little sense. You should call it conditionally in the callback that is passed to setInterval. Maybe when a certain time has passed...

JavaScript Stopwatch - Trouble Displaying a Leading Digit

I've been trying to create a simple stopwatch script using JavaScript in order to display the number of seconds, minutes, and hours that have elapsed.
Ideally, I'd like to have the time displayed as follows:
hh:mm:ss
With JavaScript, I was unable to find a built-in way to format numbers such that they contain a leading zero if a number is only one digit in length. This is where my problem lies - the logic that I added to the script to add a leading "0" works for the seconds display, but not for the minutes or hours displays.
Instead of only adding a leading "0" and then the one-digit value, the code I wrote will add in a "0" for each iteration of the setInterval() function, creating a long string of "0"s and then the current minutes or hours values.
I'm having trouble understanding why that is happening for the minutes and hours sections, but not for the seconds section when the code being used is the same.
In theory, I know that I'm essentially just adding another "0" to a string that then gets displayed each time the setInterval() function executes, but I can't seem to figure out why that doesn't happen in the seconds section. And what's also interesting is that the leading "0"s don't start getting added until the timer reaches two seconds.
Please see below for the code that I wrote for this stopwatch script. I'd certainly appreciate any insight that anyone could provide to get this working as expected.
let seconds = 0;
let minutes = 0;
let hours = 0;
function stopWatch(){
//Increment seconds on each "tick" of the stopwatch
seconds++;
//Check if minutes or hours needs to be incremented (which should happen every 60 seconds or 60 minutes, resepctively)
if(seconds / 60 == 0){
seconds = 0;
minutes++;
if(minutes / 60 == 0){
minutes = 0;
hours++;
}
}
//If the number of elapsed seconds, minutes, or hours is less than 10, add a 0 to the front of the number.
if(seconds < 10){
seconds = "0" + seconds;
}
if(minutes < 10){
minutes = "0" + minutes;
}
if(hours < 10){
hours = "0" + hours;
}
//Print the results to the "display" div in the HTML
document.getElementById("display").innerHTML = hours + ":" + minutes + ":" + seconds;
}
//Run the stopWatch() function every 1000ms
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>
And for what it's worth, I kept the <script></script> tags in the HTML document for simplicity, but once I get it working, I'll likely move the script to its own script.js file and potentially add in some buttons to start, stop, and reset the stopwatch.
let seconds = 0;
let minutes = 0;
let hours = 0;
let seconds_string = "0";
let minutes_string = "0";
let hours_string = "0";
function stopWatch(){
//Increment seconds on each "tick" of the stopwatch
seconds++;
//Check if minutes or hours needs to be incremented (which should happen every 60 seconds or 60 minutes, resepctively)
if(seconds / 60 === 1){
seconds = 0;
minutes++;
if(minutes / 60 === 1){
minutes = 0;
hours++;
}
}
//If the number of elapsed seconds, minutes, or hours is less than 10, add a 0 to the front of the number.
if(seconds < 10){
seconds_string = "0" + seconds.toString();
} else {
seconds_string = seconds.toString();
}
if(minutes < 10){
minutes_string = "0" + minutes.toString();
} else {
minutes_string = minutes.toString();
}
if(hours < 10){
hours_string = "0" + hours.toString();
} else {
hours_string = hours.toString();
}
//Print the results to the "display" div in the HTML
document.getElementById("display").innerHTML = hours_string + ":" + minutes_string + ":" + seconds_string;
}
//Run the stopWatch() function every 1000ms
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>
When you do "0" + minutes (and seconds, and hours) those variables get automatically converted into a string, consisting of two characters, a zero and something else.
Since the variables carry through each iteration, the next time you are adding another "0" character to the beginning of the string, and so-on.
The reason it's not happening to seconds is because you are converting seconds BACK to an int at the beginning of the loop when you do seconds++. So it becomes a string, then an int, then a string, etc.
To see this in action, try this snippet:
var test = 1;
console.log( typeof test ); //outputs "number"
test = "0" + test;
console.log( typeof test ); //outputs "string"
test++;
console.log( typeof test); //outputs number
My suggestion would be to separate counting units from display units. See if minutes is less than 10, and if so set outputMinutes to "0" + minutes. Do the same for seconds and hours. Then you just change the outputMinutes, outputSeconds, and outputHours each time, while the actual minutes, seconds, and hours variables remain as integers.
Instead of test in the if if the value is less than 10, test the length of that value as a string, if it is less than 2 (which means any number less than 10 in this case), then you add another "0" as a string to the value;
Like below:
let seconds = 0;
let minutes = 0;
let hours = 0;
function stopWatch(){
seconds++;
if(seconds / 60 == 0){
seconds = 0;
minutes++;
if(minutes / 60 == 0){
minutes = 0;
hours++;
}
}
if(seconds.toString().length < 2){
seconds = "0" + seconds;
}
if(minutes.toString().length < 2){
minutes = "0" + minutes;
}
if(hours.toString().length < 2){
hours = "0" + hours;
}
document.getElementById("display").innerHTML = hours + ":" + minutes + ":" + seconds;
}
window.setInterval(stopWatch, 1000);
<div id="display">00:00:00</div>

How to tween a timestamp to a specific time

I have a fake clock on screen with a time of day:
<div class="time">9:14<sup>am</sup></div>
I want to make a function to be able to tween that time to another arbitrary time,
so that the clock would actually progress through the seconds and hours until it hit the new time(pseudocode):
var currentTime = {
time: 9:14am
}
function changeTime(newTime){
TweenMax.to(currentTime,.5,{
time: newTime
});
}
changeTime(12:32pm);
So in the case above, the minutes would go up by one until they hit 60, then increment the hours by one and reset to zero, then increment again to 60, etc, until they hit 12:32 (with the am switching to pm at 12:00pm).
Is there a way to do this with tweenmax and a timestamp? Or would I need to construct a custom function? Or perhaps is there a better way to tween time?
You can use something like this (and improve it, I did this quickly).
<script>
var hour, minute, second, meridian, isAm;
isAm = true;
hour = 0;
minute = 0;
second = 0;
function timerLoop () {
second++;
if(second > 59) {
second = 0;
minute++;
}
if(minute > 59) {
minute = 0;
hour++;
}
if(hour >12) {
hour = 1;
isAm = !isAm;
}
// update labels
meridian = 'a.m.';
if(!isAm) meridian = 'p.m.';
console.log(hour + ':' + minute + ':' + second + ' ' + meridian);
setTimeout(function() {
timerLoop();
}, 1000);
}
timerLoop();
</script>
I tested it for 2 mins only but the that part was working.
You'll probably want to add leading zero's to the single digits as I haven't done that. And once it is running as you want you can look at adding animations or fades to style it a bit better.

How to add days this countdown script so that it becomes DD-HH-MM-SS?

I have this script in jQuery:
// Auction countdown script
$(function () {
var remaining = $("#countdown").text(),
regex = /\d{2}/g,
matches = remaining.match(regex),
hours = matches[0],
minutes = matches[1],
seconds = matches[2],
remainingDate = new Date();
remainingDate.setHours(hours);
remainingDate.setMinutes(minutes);
remainingDate.setSeconds(seconds);
var intvl = setInterval(function () {
var totalMs = remainingDate.getTime(),
hours, minutes, seconds;
remainingDate.setTime(totalMs - 1000);
hours = remainingDate.getHours();
minutes = remainingDate.getMinutes();
seconds = remainingDate.getSeconds();
if (hours === 0 && minutes === 0 && seconds === 0) {
alert('done');
}
$("#countdown").text(
(hours >= 10 ? hours : "0" + hours) + ":" +
(minutes >= 10 ? minutes : "0" + minutes) + ":" +
(seconds >= 10 ? seconds : "0" + seconds));
}, 1000);
});
Now, this takes a string and makes a HHMMSS countdown for it. I want it to be DDHHMMSS but I can't seem to get it to work. Can anybody point me in the right direction?
Thanks!
If you like to create countdown function by yourself then Please take reference from below links to build right logic :
http://stuntsnippets.com/javascript-countdown/
http://www.hashemian.com/tools/javascript-countdown.htm
OR
its better to use one of below jQuery plugin
http://www.littlewebthings.com/projects/countdown/
http://keith-wood.name/countdown.html
Hope it helps
ALL D BEST
The basic problem is that Date objects are for dates and times, not time intervals. So setDate() and getDate() operate on the date of the month, not a count of days.
You could simply use integers and divide by the number of seconds in a minute, minutes in an hour, etc. Or you could implement a TimeInterval object, as described here:
http://i-programmer.info/programming/javascript/3088-a-javascript-timeinterval-object.html
Use toString for that:
var remainingDate = new Date();
remainingDate.toString("dd-MM-yyyy HH:mm:ss");
This returns for example 01-08-2012 14:08:22

Using JavaScript comparison operators with current time

I am making an HTML table that should hide certain parts according to the time using JavaScript, for example;
6:30
6:45
7:05
When the current time is equal or greater than 6:30 the first cell should hide.
The way I start this is;
var now = new Date(); // to create date object
var h = now.getHours(); // to get current hour
var m = now.getMinutes(); // to get current minute
And then later;
if (h>=6 && m>=30) {
$('table#truetable tr:first').hide();
}
This does not work (I think the problem is in the last part), as it wouldn't hide this (first) cell in let's say 7:25 as the minute number then isn't greater than 30, which means this way wouldn't work in many other cases.
Can I fix this? Do I need to do it another way?
Compare by minutes:
if( h*60+m/*h:m*/ >= 6*60+30/*6:30*/ ){
}
The easiest way is to handle the case when it's 6 o'clock separately:
if (h > 6 || (h == 6 && m >= 30)) {
// Modify DOM
}
var t = new Date()
undefined
t.getHours()
20
t.getHours()>=6
true
h = t.getMinutes()
51
t>=30
true
This does work. your problem is that you are checking for time and minutes, which mean that if the minutes are lesser than 30 it will return false.
Your if translates to:
any hour bigger than six whose minutes are also bigger than 30
Your if condition should be:
if(h>=6 && m>=30 || h>=7)
or with numbers only
if(h*60+m>= 390)
I wrote a function to convert a time in the hh:mm or hh:mm:ss format to seconds. You can find it below:
function hourConvert(str) {
//this separates the string into an array with two parts,
//the first part is the hours, the second the minutes
//possibly the third part is the seconds
str = str.split(":");
//multiply the hours and minutes respectively with 3600 and 60
seconds = str[0] * 3600 + str[1] * 60;
//if the there were seconds present, also add them in
if (str.length == 3) seconds = seconds + str[2];
return seconds;
}
It is now easy to compare times with each other:
if (hourConvert(str) > hourConvert("6:30")) //Do Stuff
See it in action: http://jsfiddle.net/TsEdv/1/

Categories

Resources