Adding zeros in a digital clock - javascript

I have researched for an hour now on how to do add the zeros whenever hours, minutes or seconds are less 10, to make them, for example, "05 hours", and not just "5 hours".
I have tried if (hours < 10) { hours = "0" + hours } and I've seen it work in a couple of websites, but it doesn't seem to work in my code.
How can I make this work?
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>

That is because you need to calculate date1 and actualdate after prepending zeroes on the values.
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>
I would suggest you to use padStart of ES8 to do this task.
var x = "5";
console.log(x.padStart(2, "0"));

Better use this pad function :
function pad(num, size) {
var s = num+"";
while (s.length < size) s = "0" + s;
return s;
}
in node :
> function pad(num, size) {
... var s = num+"";
... while (s.length < size) s = "0" + s;
... return s;
... }
> pad(1, 2)
'01'
> pad(11, 2)
'11'
>

if (seconds < 10) { seconds = "0" + seconds; } this will just add the number 0 to the number of seconds. So you have to make your numbers a string:
function clock() {
//Clock variables
var today = new Date();
var hours = today.getHours().toString();
var minutes = today.getMinutes().toString();
var seconds = today.getSeconds().toString();
//Adding zeros, but it doesn't work.
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var date1 = [hours, minutes, seconds];
var actualDate = date1.join(":");
//text
document.getElementById("hey").innerHTML = actualDate;
//Repeat every 1000ms (1 second)
setTimeout(clock, 1000);
};
clock();
<h1 id="hey"></h1>

Related

Subtract time and show difference in mins:secs format

I want to accurately display the difference between two times. The different should be displayed in a format such as mm:ss
methods: {
calcuateTimeDifference: function (startTime, endTime) {
let result = 0;
if (startTime && endTime) {
let start = startTime.split(":");
let end = endTime.split(':');
let startTimeInHrs = (parseFloat(start[0]/3600) + parseFloat(start[1]/60) + parseFloat(start[2]/3600));
let endTimeInHrs = (parseFloat(end[0]/3600) + parseFloat(end[1]/60) + parseFloat(end[2] /3600));
result = endTimeInHrs - startTimeInHrs;
}
return result.toFixed(2);
},
Using this function - the difference between the following times: 16:03:01 - 16:04:01 - I get the result as -32.00.
split the strings on : to get the hours, minutes, and seconds
convert all to seconds and add them to get the total seconds from each time
subtract the two to get the difference in seconds
convert the difference seconds to hours, minutes and seconds using the modules operator(%)
format the result for appropriate display
let start = "16:03:01";
let end = "16:04:05";
let time = calcuateTimeDifference(start, end);
console.log(time);
function calcuateTimeDifference(startTime, endTime) {
let result = 0;
if (startTime && endTime) {
const start = startTime.split(':').map(Number);
const end = endTime.split(':').map(Number);
const startSeconds = (60*60) * start[0] + 60*start[1] + start[2];
const endSeconds = (60*60) * end[0] + 60*end[1] + end[2];
const diffSeconds = endSeconds - startSeconds;
seconds = parseInt((diffSeconds) % 60);
minutes = parseInt((diffSeconds/60) % 60);
hours = parseInt((diffSeconds/(60*60)) % 24);
//append `0` infront if a single digit
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return `${hours}:${minutes}:${seconds}`;
}
console.log("Invalid Input");
}
function calcuateTimeDifference(startTime, endTime) {
let toSeconds = (time) => {
let [h, m, s] = time.split(':');
return h * 360 + m * 60 + +s;
};
let d = Math.abs(toSeconds(startTime) - toSeconds(endTime));
let mm = String(Math.floor(d / 60));
if (mm.length == 1) mm = '0' + mm;
let ss = String(d % 60);
if (ss.length == 1) ss = '0' + ss;
return `${mm}:${ss}`;
}

current time using javascript not grabbing correct location

Running a script to get current time for two specific locations. One time is for Mountain Time and the other is for East Coast Time. I am running into an issue where the Mountain Time clock is displaying time based on Pacific Standard Time if a user is based in a PST location. Rather than having PST is there a way for me to make sure that the two clocks are only getting MT and ET and taking into consideration daylight savings time as well?
$(document).ready(function(){
function timeDisplay() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if(hours >= 12){
hours = hours - 12;
meridiem = "pm";
}
else{
meridiem = "am";
}
if(hours === 0){
hours = 12;
}
if(hours < 10){
hours = "0" + hours;
}
if(minutes < 10){
minutes = "0" + minutes;
}
var clockDiv = document.getElementById('stat');
clockDiv.innerText = hours + ":" + minutes + meridiem;
}
timeDisplay();
setInterval(timeDisplay, 1000);
function newYorkTimeDisplay(offset) {
var currentTime = new Date();
currentTime.setHours(currentTime.getHours()+offset);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if(hours >= 12){
hours = hours - 12;
meridiem = "pm";
}
else{
meridiem = "am";
}
if(hours === 0){
hours = 12;
}
if(hours < 10){
hours = "0" + hours;
}
if(minutes < 10){
minutes = "0" + minutes;
}
var newYorkDiv = document.getElementById('newYork');
newYorkDiv.innerText = hours + ":" + minutes + meridiem;
}
newYorkTimeDisplay(+2);
setInterval(newYorkTimeDisplay, 1000, +2);
});
Any help on this is appreciated. Trying to figure out what I am missing.
Thanks in advance.
You need to get the user's current UTC timezone offset and subtract it from New York's Timezone Offset.
var tz_offset = (new Date().getTimezoneOffset()/100) - 3;
newYorkTimeDisplay(tz_offset);
$(document).ready(function() {
function timeDisplay() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if (hours >= 12) {
hours = hours - 12;
meridiem = "pm";
} else {
meridiem = "am";
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
var clockDiv = document.getElementById('stat');
clockDiv.innerText = hours + ":" + minutes + meridiem;
}
timeDisplay();
setInterval(timeDisplay, 1000);
function newYorkTimeDisplay(offset) {
var currentTime = new Date();
currentTime.setHours(currentTime.getHours() + offset);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if (hours >= 12) {
hours = hours - 12;
meridiem = "pm";
} else {
meridiem = "am";
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
var newYorkDiv = document.getElementById('newYork');
newYorkDiv.innerText = hours + ":" + minutes + meridiem;
}
var tz_offset = (new Date().getTimezoneOffset()/100) - 3;
newYorkTimeDisplay(tz_offset);
setInterval(newYorkTimeDisplay, 1000, +2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=newYork></div>
<div id=stat></div>

Auto-updatable values in angularJS

I have array of dates $scope.dates = [] ($scope.dates[0].date). I need to create another array with auto-updateble(!) values of durations.
$scope.dates[i].duration = Date.now() - $scope.dates[i].date.
I want to create timer in seconds:
<tr ng-repeat="x in dates">
<td>{{x.date | date:'HH:mm:ss'}}</td>
<td>{{x.duration}}</td>
Edit: Probled solved
Call this function, it will maintain object in $rootScope object:
$rootScope.timerActivate = function () {
console.log('activateTimer ::');
if(!$rootScope.time)
{
$rootScope.time = {}
}
var countDown = function () {
var today = new Date();
var hours = new Date().getHours();
var hours = (hours + 24) % 24;
var mid = 'am';
if (hours == 0) { //At 00 hours we need to show 12 am
hours = 12;
}
else if (hours > 12)
{
hours = hours % 12;
mid = 'pm';
}
var minute = today.getMinutes();
var sec = today.getSeconds();
$rootScope.time.hours = (hours < 10) ? '0' + hours : hours;
$rootScope.time.minutes = (minute < 10) ? '0' + minute : minute;
$rootScope.time.seconds = (sec < 10) ? '0' + sec : sec;
$rootScope.time.blink = (sec % 2) ? ':' : ' ';
$rootScope.time.mid = mid;
$timeout(countDown, 1000);
};
$timeout(countDown, 1000);
};
You should use $interval. https://docs.angularjs.org/api/ng/service/$interval

Countdown HH:MM:SS in Jquery

I want to countdown timer in format of hh:mm:ss so I use this code it's convert seconds into required format but when I count down it display me NaN. Can you tell me what I am doing wrong
Here is code
<div id="timer"></div>
JS
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Here is JsFiddle link CountDown Timer
Well, let's take a look at what your code does:
Set count to the string value 62.
Convert it to HHMMSS, so now count is equal to the string 00:01:02
Start the timer.
On the first run of the timer, decrement count. Erm... count is a string, you can't decrement it. The result is not a number.
Okay, so with that out of the, way how about fixing it:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
var count = '62'; // it's 00:01:02
var counter = setInterval(timer, 1000);
function timer() {
if (parseInt(count) <= 0) {
clearInterval(counter);
return;
}
var temp = count.toHHMMSS();
count = (parseInt(count) - 1).toString();
$('#timer').html(temp);
}
http://jsfiddle.net/5LWgN/17/
If you use the jquery moment plugin. If you are not using jQuery moment then you can use formatTime(seconds) function that is in the #Niet's answer https://stackoverflow.com/a/18506677/3184195
var start_time = 0;
var start_timer = null;
start_timer = setInterval(function() {
start_time++;
var formate_time = moment.utc(start_time * 1000).format('mm:ss');
$('#Duration').text(formate_time);
}, 1000);
});
function clear() {
if (start_timer) clearInterval(start_timer);
}

How to make Javascript time automatically update

I am using the following Javascript code to display the time on my website. How can I make this update automatically.
Thanks
<section class="portlet grid_6 leading">
<header>
<h2>Time<span id="time_span"></span></h2>
</header>
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
var t_str = hours + ":" + minutes + " ";
if(hours > 11){
t_str += "PM";
} else {
t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
</script>
</section>
Use setTimeout(..) to call a function after a specific time. In this specific case, it is better to use setInterval(..)
function updateTime(){
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
var t_str = hours + ":" + minutes + " ";
if(hours > 11){
t_str += "PM";
} else {
t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
}
setInterval(updateTime, 1000);
Add all your javascript code in a function called updateClock() placed in the <head> section of your page, and alter the <body> tag that way:
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
It will recalculate and redisplay the time every second. Since you only display hours and minutes, you can use a longer interval. If you want to update time every numSeconds you should use something like
<body onload="updateClock(); setInterval('updateClock()', numSeconds * 1000 )">
And of course, this one is just one of many gazillions solutions that you can find out there.
There are plenty of clock libraries out there. Perhaps check out this previous post: How to create a jquery clock timer
try this, a tidier version:
var el = document.getElementById('time_span')
setInterval(function() {
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes(),
ampm = hours > 11 ? 'PM' : 'AM';
hours += hours < 10 ? '0' : '';
minutes += minutes < 10 ? '0' : '';
el.innerHTML = hours + ":" + minutes + " " + ampm;
}, 1000);
GetTime();
function GetTime(){
var CurrentTime = new Date()
var hour = CurrentTime.getHours()
var minute = CurrentTime.getMinutes()
var second = CurrentTime.getSeconds()
if(minute < 10){
minute = "0" + minute
}
if(second < 10){
second = "0" + second
}
var GetCurrentTime = hour + ":" + minute + ":" + second + " ";
if(hour > 11){
GetCurrentTime += "p.m."
}else{
GetCurrentTime += "a.m."
}
document.getElementById("CurrentTime").innerHTML = GetCurrentTime;
setTimeout(GetTime,1000)
}
<span id="CurrentTime"></span>
A bit less messy would be:
timer();
function timer(){
var now = new Date,
hours = now.getHours(),
ampm = hours<12 ? ' AM' : ' PM',
minutes = now.getMinutes(),
seconds = now.getSeconds(),
t_str = [hours-12, //otherwise: what's the use of AM/PM?
(minutes < 10 ? "0" + minutes : minutes),
(seconds < 10 ? "0" + seconds : seconds)]
.join(':') + ampm;
document.getElementById('time_span').innerHTML = t_str;
setTimeout(timer,1000);
}
The timer updates (roughly) every second (= 1000 Ms), using setTimeout from within the timer function.
​See it in action
This code output format->00:00:00 and refresh automatically like real time clock, hope it works..
function r(txt) {
document.write(tex);
}
function createTIME() {
d = new Date();
var time = addZERO(d.getHours()) + ':' + addZERO(d.getMinutes()) + ':' + addZERO(d.getSeconds());
return 'Present Time = ' + time;
}
function doDyn() {
document.getElementById('Dyn').innerHTML = createTIME();
}
function addZERO(val) {
return ((val < 10) ? '0' : '') + val;
}
GetTime();
function GetTime(){
var CurrentTime = new Date()
var hour = CurrentTime.getHours()
var minute = CurrentTime.getMinutes()
var second = CurrentTime.getSeconds()
if(minute < 10){
minute = "0" + minute
}
if(second < 10){
second = "0" + second
}
var GetCurrentTime = hour + ":" + minute + ":" + second + " ";
if(hour > 11){
GetCurrentTime += "p.m."
}else{
GetCurrentTime += "a.m."
}
<!-- Try changing innerHTML to document.getElementById("CurrentTime").value -->
document.getElementById("CurrentTime").value = GetCurrentTime;
setTimeout(GetTime,1000)
}
<span id="CurrentTime"></span>
timer();
function timer(){
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var sec = currentTime.getSeconds()
if (minutes < 10){
minutes = "0" + minutes
}
if (sec < 10){
sec = "0" + sec
}
var t_str = hours + ":" + minutes + ":" + sec + " ";
if(hours > 11){
t_str += "PM";
} else {
t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
setTimeout(timer,1000);
}
<header>
<h2>Time<span id="time_span"></span></h2>
</header>

Categories

Resources