I constructed a small clock out of Javascript code, and it fails to update correctly. It display's the time fine, but you have to refresh the page in order to get the clock to update correctly. Is there a way I can have my code update automatically without having to update the page every time?
Picture:
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>")
</script>
First of all, you could wrap your code in a function, say, currentTime(), changing the document.write call to a return statement, so you have a function currentTime() that returns the updated string. Then save somewhere a handle to an HTML element where you want to show the updated time, like el = document.getElementById('time'), and then use an interval like so
setInterval(function () {
el.innerHTML = currentTime();
}, 5000);
function UpdateClock(){
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10)
minutes = "0" + minutes
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
//document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
document.getElementById('myClock').innerHTML = "<b>" + hours + ":" + minutes + " " + suffix + "</b>";
}
setInterval(function(){ UpdateClock(); }, 6000);
HTML:
<div id="myClock"></div>
Related
I need to display the time and the minutes are not working correctly. It is returning 12:4, 2:3..when the minutes are less than 10 there is not 0. I tried adding the "0" like this:
var formattedTime = new Date(time + 'z');
var hours = formattedTime.getHours();
var amOrPm = hours >= 12 ? 'PM' : 'AM';
hours = (hours % 12) || 12;
var minutes = formattedTime.getMinutes();
if (minutes < 10) {
("0" + minutes)
};
var finalTime = eventDate +" "+ hours + ":" + minutes + " " + amOrPm;
Any help is welcome(I am new to coding). Thank You.
The statement ("0" + minutes) doesn't do anything. It does add a '0' to minutes, but you're not doing anything with the result. The problem is that you need to set the result of this statement in a new variable.
But here's an easier way to do this:
const minutes = 5;
const minuteStr = minutes.toString().padStart(2, '0');
I'm trying to create a script in Javascript that shows when a page was last modified, which returns the date, time, in am or pm format, of modification.
Clearly I am doing something wrong. I can't get the script to run, and it will be in my function AmPm. Can someone please help?
// Javascript code for page modification
// Shows the date, time, am or pm, of modification.
// This section sets the date of modification
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "." + (modiDate.getMonth() + 1) + "." + modiDate.getFullYear();
return showAs
}
// This section sets the time of modification
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
// This section writes the above in the document
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
// This section decides if its am or pm
function AmPm() {
var hours = new Date().getHours();
var hours = (hours + 24 - 2) % 24;
var mid = 'AM';
if (hours == 0) { // At 00 hours (midnight) we need to display 12 am
hours = 12;
} else if (hours > 12) // At 12pm (Midday) we need to display 12 pm
{
hours = hours % 12;
mid = 'PM';
}
}
var mid = //This is where I am stuck!!
return AmPm
document.write("This webpage was last edited on: ");
document.write(lastModified() + " at " + GetTime() + AmPm());
document.write("");
document.write(" NZ Daylight Savings Time.");
document.write("");
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
I have the following code, which is supposed to do what I need:
function fromSeconds(seconds, showHours = false) {
if(showHours) {
var hours = Math.floor(seconds / 3600),
seconds = seconds - hours * 3600;
}
var minutes = (Math.floor(seconds/60) < 10) ?
"0" + Math.floor(seconds/60) : Math.floor(seconds/60);
var seconds = (seconds % 60 > 9) ? seconds % 60 : "0" + seconds % 60;
if(showHours) {
var timestring = hours + ":" + minutes + ":" + seconds;
} else {
var timestring = minutes + ":" + seconds;
}
return timestring;
}
The problems is that I also have this:
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function() {
$('#currentTime').html(video[0].currentTime.toFixed(2));
$('#remTime').html((video[0].duration - video[0].currentTime).toFixed(2));
$('#totalTime').html(video[0].duration.toFixed(2));
});
And I don't know how to apply the first code so that for example currentTime is displayed like this: minutes:seconds.
Any help please?
With a small fixation you can leave this as that:
Demo
function fromSeconds(seconds, showHours) {
if(showHours) {
var hours = Math.floor(seconds / 3600),
seconds = seconds - hours * 3600;
}
var minutes = ("0" + Math.floor(seconds/60)).slice(-2);
var seconds = ("0" + parseInt(seconds%60,10)).slice(-2);
if(showHours) {
var timestring = hours + ":" + minutes + ":" + seconds;
} else {
var timestring = minutes + ":" + seconds;
}
return timestring;
}
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
$('#currentTime').html(fromSeconds(video[0].currentTime));
$('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
$('#totalTime').html(fromSeconds(video[0].duration));
});
You can just pass the values like video[0].currentTime to the function fromSeconds which will return the formatted string
var video = $('#home_explainer_placeholder');
video.bind("timeupdate", function () {
$('#currentTime').html(fromSeconds(video[0].currentTime));
$('#remTime').html(fromSeconds(video[0].duration - video[0].currentTime));
$('#totalTime').html(fromSeconds(video[0].duration));
});
Assuming currentTime is the time in seconds, you need to pass the value into your function.
fromSeconds returns the text your require, so fromSeconds(mytimevalue) will return mm:ss as required:
video.bind("timeupdate", function() {
$('#currentTime').html( fromSeconds(video[0].currentTime) );
$('#remTime').html( fromSeconds(video[0].duration - video[0].currentTime) );
$('#totalTime').html( fromSeconds(video[0].duration) );
});
Another option would be to use JavaScript's Date() Object, which takes milliseconds as a value:
var currentTime = new Date(video[0].currentTime * 1000);
You can then use Date.getMinutes() and Date.getSeconds() to find your values.
More details here
$('#currentTime').html(function(){
var time=video[0].currentTime.toFixed(2);
//some conversion needed in-order to convert to required format
fromSeconds(time,false)//returns time
});
I would like the time to reset every second so the clock becomes a running one. I'm a javascript noob and I couldn't find any solution anywhere.
<!--
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
document.write("<b>" + day + "/" + month + "/" + year + "</b>")
//-->
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10)
minutes = "0" + minutes
if (seconds < 10)
seconds = "0" + seconds
document.write(hours + ":" + minutes + ":" + seconds)
var myInterval = window.setInterval(function() {
window.document.write(hours + ":" + minutes + ":" + seconds);
}, 1000);
Later you can stop it with
window.clearInterval(myInterval);
We assign the return value of setInterval (an ID in the form of a number) to a variable because we'll need it later to stop our particular interval using the clearInterval function. If we don't do that, there will be no way (without certain hacks) to stop the interval.
For that you need to use the window.setInterval method. Please look at this page for more information: http://www.w3schools.com/js/js_timing.asp
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>