My getTime function shows me the current hour, minutes, and seconds without any problem.
My question is how can I call the hours, minutes, and seconds on different spans?
Example
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
JavaScript Function
<script language="JavaScript">
function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
//timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
const hoursSpan = document.getElementById('Hour');
setInterval(() => {
hoursSpan.textContent = getTime();
}, 1000);
</script>
Try this. Make the variables global to get separate values of hours minutes and seconds. You were using wrong id to get span and the function returns full string so splitted it for only hours
var timeNow = new Date();
var hours = timeNow.getHours();
var minutes = timeNow.getMinutes();
var seconds = timeNow.getSeconds();
function getTime() {
timeNow = new Date();
hours = timeNow.getHours();
minutes = timeNow.getMinutes();
seconds = timeNow.getSeconds();
let timeString = '' + ((hours > 24) ? hours - 12 : hours);
timeString += ((minutes < 10) ? ":0" : ":") + minutes;
timeString += ((seconds < 10) ? ":0" : ":") + seconds;
timeString += (hours >= 12) ? "" : "";
//timeString += (hours >= 12) ? " P.M." : " A.M.";
return timeString;
}
const hoursSpan = document.getElementById('hours');
const min = document.getElementById('minutes');
const sec = document.getElementById('seconds');
setInterval(() => {
hoursSpan.textContent = getTime().split(':')[0];
min.textContent=":"+minutes;
sec.textContent=":"+seconds;
}, 1000);
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
First issue
You have a silly mistake in this line
const hoursSpan = document.getElementById('Hour');
There is no element with the id Hour. Your span element has id hours. You need this instead:
const hoursSpan = document.getElementById('hours');
Second issue
If you plan to use the 3 parts separately, then why join them into a string in the first place? Just make use of the fact that JavaScript functions can return objects!
This looks a lot cleaner!
<span id="hours" class="x"></span>
<span id="minutes" class="y"></span>
<span id="seconds" class="z"></span>
<script>
function getTime() {
const timeNow = new Date();
const hours = timeNow.getHours();
const minutes = timeNow.getMinutes();
const seconds = timeNow.getSeconds();
let hoursString = '' + ((hours > 12) ? hours - 12 : hours);
let minutesString = ((minutes < 10) ? ":0" : ":") + minutes;
let secondsString = ((seconds < 10) ? ":0" : ":") + seconds;
return {
h: hoursString,
m: minutesString,
s: secondsString
};
}
const hoursSpan = document.getElementById('hours');
const minutesSpan = document.getElementById('minutes');
const secondsSpan = document.getElementById('seconds');
setInterval(() => {
const t = getTime();
hoursSpan.textContent = t.h;
minutesSpan.textContent = t.m;
secondsSpan.textContent = t.s;
}, 1000);
</script>
PS: This code could be shortened a lot, but I kept it this way so it's easy to understand.
Related
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}`;
}
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>
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>
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
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>