Need to display current time in JS with the given functions.
Internet searches showed JS using Date() and Time() for gathering the info, but the date and time are not showing up in the HTML when run it.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var displayCurrentTime = function() {
var now = new Date(); //use the 'now' variable in all calculations, etc.
var Date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hours = now.getHours()+ ":" + now.getMinutes() + ":"
+ now.getSeconds();
//Ok, problem now is getting HTML to call it up?
};
var padSingleDigit = function(num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
window.onload = function() {
// set initial clock display and then set interval timer to display
// new time every second. Don't store timer object because it
// won't be needed - clock will just run.
};
Instructor's instructions:
"Note that to convert the computer’s time from a 24-hour clock to a 12-hour clock, first check to see if the hours value is greater than 12. If so, subtract 12 from the hours value and set the AM/PM value to “PM”. Also, be aware that the hours value for midnight is 0.
The starter project has four functions supplied: the $ function, the start of a displayCurrentTime() function, a padSingleDigit() function that adds a leading zero to single digits, and the start of an onload event handler.
In the displayCurrentTime() function, add code that uses the Date object to determine the current hour, minute, and second. Convert these values to a 12hour clock, determine the AM/PM value, and display these values in the appropriate span tags.
Then, in the onload event handler, code a timer that calls the displayCurrentTime() function at 1 second intervals. Also, make sure that the current time shows as soon as the page loads. (some comments have been included in the starter code to guide you on where to place things)."
In order to grap an html element you first need one. So i made a tag with an id of "clock". I then set an interval, running every 1000 milis (1 second) to give me the correctly formatted time.
clock = document.getElementById("clock");
let hours, minutes, seconds;
function checkDigits(num, hours) {
if (num < 10) {
return "0" + num
} else {
if (hours) {
return num - 12
}
return num
}
}
function updateTime() {
date = new Date();
hours = checkDigits(date.getHours(), true)
minutes = checkDigits(date.getMinutes())
seconds = checkDigits(date.getSeconds())
clock.innerHTML = hours + ":" + minutes + ":" + seconds;
}
window.onload = function() {
setInterval(function() {
updateTime()
}, 1000);
}
<h1 id="clock"></h1>
Related
I'm trying to edit following code to get the output I want.
function zoo_countdown_end_day() {
if ($('.zoo-get-order-notice .end-of-day')[0]) {
var offset = $('.end-of-day').data('timezone');
var day = new Date();
var utc = day.getTime() + (day.getTimezoneOffset() * 60000);
let d = new Date(utc + (3600000*offset)),
duration = 60 * (60 - d.getMinutes());
let timer = duration, minutes;
let hours = (23 - d.getHours());//kumudu edited this
hours = hours < 10 ? '0' + hours : hours;
let label_h = $('.zoo-get-order-notice .end-of-day').data('hours');
let label_m = $('.zoo-get-order-notice .end-of-day').data('minutes');
setInterval(function () {
minutes = parseInt(timer / 60, 10);
minutes = minutes < 10 ? "1" + minutes : minutes;
$('.zoo-get-order-notice .end-of-day').text(hours + ' ' + label_h + ' ' + minutes + ' ' + label_m);
if (--timer < 0) {
timer = duration;
}
}, 1000);
}
}
zoo_countdown_end_day();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
This is the current output:
I just want to edit countdown time to countdown from next day 4.00 P.M (hours and minuets). Because I offer next day shipping.
Ok, the long and short of this answer is that it uses 2 functions to help..
countDown: this function takes in a functionwhileCountingDown, a numberforHowLong, then another functionwhenFinishedThen
whileCountingDown being triggered EACH second with the parameter being the amount of time left in seconds
forHowLong is the amount of seconds this countdown will last
whenFinishedThen is a function that activates AFTER the countdown is over.. it can be anything(like making a new countdown as well)
timeParse: this function takes in a numberseconds and then returns a string that looks like a more human version of time
eg: timeParse(108010), 108010 is 30 hours and 10 seconds, and it would return "1 day, 6 hours, 0 minutes"
The combination of these functions are able to have a countdown system working very well.. I ALSO DO NOT KNOW WHERE YOU GET YOUR FUTURE TIME FROM,
but if you get it in a timestamp format(like 1611860671302, a value that I copied from new Date().getTime() as I was typing this),
the line where you see 30*3600, replace that line with ((dateStamp-new Date().getTime())/1000).toFixed(0)
//honestly I don't even see where it's counting down from so i just made a countdown function that works in seconds and scheduled 30 hours from now(from when you run code).. just the format would probably need changing(since i don't know what format you want)
function zoo_countdown_end_day() {
var elem=$('.zoo-get-order-notice .end-of-day')[0]
//like I said, I didn't even see where you're taking the future time from but I'll just give a future time the equivalent of +30 hours
countDown(
(t)=>elem.innerText=timeParse(t), //every second, remaining time shows in specified element
30*3600, //seconds equivalent for 30 hours.. if you have a future dateStamp, before the countdown function, let dateStamp=this datestamp you would have, THEN change this line to.. ((dateStamp-new Date().getTime())/1000).toFixed(0)
()=>console.log("Timer Complete")
)
}
zoo_countdown_end_day();
//...............................................................
//time parsing function(takes in seconds and returns a string of a formatted date[this is what can change to change the look])
function timeParse(seconds){
var words=[
(num)=>{if(num==1){return("second")}return("seconds")},//this would return a word for seconds
(num)=>{if(num==1){return("minute")}return("minutes")},//this would return a word for minutes
(num)=>{if(num==1){return("hour")}return("hours")},//this would return a word for hours
(num)=>{if(num==1){return("day")}return("days")}//this would return a word for days
]
var timeArr=[seconds]
if(timeArr[0]>=60){//if seconds >= 1 minute
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=60){//if minutes >= 1 hour
timeArr.unshift(Math.floor(timeArr[0]/60))
timeArr[1]=timeArr[1]%60
if(timeArr[0]>=24){//if hours >= 1 day
timeArr.unshift(Math.floor(timeArr[0]/24))
timeArr[1]=timeArr[1]%24
}
}
}
timeArr=timeArr.reverse()
.map((a,i)=>`${a} ${words[i](a)}`)
.reverse() //puts words to values and then reverses it back to correct order
timeArr.splice(timeArr.length-1,1) //takes out seconds part from being returned leaving days, minutes and hours
return(timeArr.join(', ')) //a mixture/combination of the forEach formatting(joining numbers with words), what is returned from words array and how they're joined contributes to the formatted look
}
//...............................................................
//countDown function(that works in seconds)
function countDown(whileCountingDown, forHowLong, whenFinishedThen){
//basic run down is, whileCountingDown is a function, forHowLong is a number, whenFinishedThen is a function
//in depth run down is:
/*
whileCountingDown(with parameter of how much time left in seconds) is activated every second until forHowLong seconds has passed, then whenFinishedThen is triggered
*/
var i=setInterval(()=>{forHowLong--
if(forHowLong<=0){//count finished, determine what happens next
clearInterval(i); whenFinishedThen()
}
else{whileCountingDown(forHowLong)}//do this for each second of countdown
},1000)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
<span class="end-of-day"
data-timezone="+3"
data-hours="1"
data-minutes="3"></span>
</div>
I was creating a webpage and I would like to receive assistance in that. I need a text to popup when the UTCHours and UTCMinutes are equal to specific values. I want something like this. This is like the model , not actual code.
h = utcTime
m = utcminutes
if (h=x and m=y)
{
function myFunction();
}
Surely I wont do everything for you, but here you go. A base to start from.
// The button functionality
const $ = (x) => document.getElementById(x);
$('start').addEventListener('click', ()=>{
startTime();
});
$('stop').addEventListener('click', ()=>{
stopTime();
});
// The timer
// set variables
let date,
start,
stop;
function startTime() {
date = new Date(); // get current date.
start = date.getTime(); // get time from current date
// Just output
document.getElementById("showStart").innerHTML = start;
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
document.getElementById("difference").innerHTML = stop-start;
}
jsfiddle
I was bored so here you go.
// The button functionality
const $ = (x) => document.getElementById(x);
$('setAlert').addEventListener('click', ()=>{
setAlert(3); // alert in x seconds.
});
// set variables
let date,
target,
stop,
interval = 1; // integer.
function setAlert(time) {
date = new Date(); // get current date.
target = date.getTime() + ( (time * 1000) - ((interval * 1000) +1000) ); // sets the time it should alert.
/*
* time -1 because it's a 1s interval, that means when it reaches x = y it will alert 1s later by the next "check". This why you need to subtract 1s.
* (time-1)*1000 is because the getTime returns time in ms not in seconds. You would need to make it setAlert(3000),
* i made it bit easier by multiplying the value by 1000 = ms.
*/
// The loop that checks time
setInterval(function(){ // This function makes the "checking each X ms"
if(stop !== target){ // Check if time was reached.
stopTime(); // Check time
}else{
alert("TIME IS OVER"); // When time is reached do this.
}
}, interval*1000); // Refreshes the time each second.
// Just output
document.getElementById("showTarget").innerHTML = target+(interval*1000); // Because the target time has "minus" in it (line 16) it needs to be added to show the real target time.
}
function stopTime() {
date = new Date(); // get current date.
stop = date.getTime(); // get time from current date
// just output
document.getElementById("showStop").innerHTML = stop;
// document.getElementById("difference").innerHTML = stop-target;
}
jsfiddle v2
function displayAlert(hour,minute){
//create a new Date Object(Current Date and Time)
var date = new Date();
// getUTCHours getUTCMinutes are inbuilt methods
// for getting UTC hour and minute by comparing it with timezone
var utcHour = date.getUTCHours();
var utcMinutes = date.getUTCMinutes();
//display alert when utc hour and minute matches sired time
if(utcHour == hour && utcMinutes == minute){
alert(utcHour + " : " + utcMinutes)
}
}
displayAlert(18,31)
setInterval(function(){
now = new Date();
hours = now.getUTCHours();
mins = now.getUTCMinutes();
executeFunctionIfEqualToDefined(hours, mins);
},60000); // this block will run every 60000 milli seconds i.e 60 seconds =1 min
function executeFunctionIfEqualToDefined(hours, mins){
if(hours === x && mins === y){
//execute your code here
}
}
Looking for a Script that will autho refresh page on scheduled local time clock.
Twise a day. Let's say at 8AM and 8PM,
every day, OR
specific week day, cush as Mon-Fri, Mon-Wed, etc.
Notice: recently, found below code and tried this but it doesn't not work. Looking for a proper script based on above description.
setInterval(function(){
var dt = new Date();
var clock_time = dt.getHours() + ":" + dt.getMinutes();
if ( clock_time === '22:10' ) {
location.reload();
}
You have left out the time in setInterval.
You can set 2 times using || (OR) operator.
let interval; // Use clearInterval(interval) to stop the interval
let refreshDelay = 60000; // Every minute
function scheduledReload() {
let dt = new Date();
let time = dt.getHours() + ":" + dt.getMinutes();
if(time ==='08:10' || time === '22:10') {
location.reload();
}
}
interval = setInterval(scheduledReload, refreshDelay);
I am making a countdown timer that should be reseting and starting anew every 10 seconds.
This is the code I came up with by now:
function count(){
var end_date = new Date().getTime()+10*1000;
setInterval(function(){
var current_date = new Date().getTime();
var seconds_left = parseInt((end_date - current_date) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds ";
}, 1000);
}
setInterval(function(){count()}, 10*1000);
It is supposed to function as follows:
+ I set interval that will restart count() every 10 seconds.
+ count() defines end_date - a date 10 seconds from now.
+ then count() sets interval that will restart every 1 second.
+ every 1 second seconds_left variable is changed according to how current_date changed with respect to end_date.
+ as soon as seconds_left becomes 0, setInterval from step 1 fires and starts count() anew.
Which step am I implementing the wrong way? Do I misunderstand the functioning of setInterval()?
Here is my JsFiddle: http://jsfiddle.net/sy5stjun/ .
My guess is that each call is in its own new object and you get multiple instances of itself fighting ever 10 seconds.
Using your approach using date objects here is a possible re-write:
var tmr = null;
var time;
function bigInterval() {
clearInterval(tmr);
time = (new Date()).valueOf() + (10 * 1000);
smallInterval();
tmr = setInterval(smallInterval, 500);
}
function smallInterval() {
var cur = (new Date()).valueOf();
var seconds_left = parseInt((time - cur) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds";
}
bigInterval();
setInterval(bigInterval, 10*1000);
In the above code I've updated the small timer to be 500ms instead of 1000ms as it won't exactly line up with the system clock at 1000 and you get visual jumps in the numbers.
If exact timing isn't 100% important then here is a possible shorter method:
var t = 10;
setInterval(function() {
document.getElementById("countdown").innerHTML = t + " seconds";
t--;
if (t <= 0) {
t = 10;
}
}, 1000);
There are a few things going on, here. You're not specific why you have to set another interval inside your loop, but there are a lot easier ways to accomplish what you're going for. Another approach follows:
HTML:
<!-- string concatenation is expensive in any language.
Only update what has to change to optimize -->
<h1 id='countdown'><span id="ct"></span> seconds </h1>
JS:
// For one thing, grabbing a new reference to the
// dom object each interval is wasteful, and could interfere with
// timing, so get it outside your timer, and store it in a var scoped
// appropriately.
var ct = document.getElementById("ct");
// set your start
var ctStart = 10;
// set your counter to the start
var ctDown = ctStart;
var count = function() {
// decrement your counter
ctDown = ctDown - 1;
// update the DOM
ct.innerHTML = ctDown;
// if you get to 0, reset your counter
if(ctDown == 0) { ctDown = ctStart; }
};
// save a reference to the interval, in case you need to cancel it
// Also, you only need to include a reference to the function you're
// trying to call, here. You don't need to wrap it in an anonymous function
var timer = window.setInterval(count, 1000);
My jsFiddle available for tinkering, here: http://jsfiddle.net/21d7rf6s/
I'm trying to do a program which executes after 15 minutes of being in the page. My problem is how to get the exact number to add on the timestamp which is stored in a cookie.
I need a function to convert seconds into timestamps or anything that can make the action execute after 15 minutes. I don't really know how much time is 1792939 which I place in the code below.
setInterval("timer()",1000);
$.cookie("tymz", time);
function timer(){
var d = new Date();
var time = d.getTime();
var x = Number($.cookie("tymz")) + 1792939;
//alert('Cookie time: ' + x + '\nTime: ' + time);
if(time > x){
alert('times up');
}else{
//alert('not yet\n' + 'times up: ' + x + '\ntime: ' + time);
}
}
How about using setTimeout(..)?
<script type="text/javascript">
function myFunc()
{
alert("I will show up 15 minutes after this pages loads!");
}
setTimeout("myFunc()",60*15*1000);
</script>
Check this: http://www.w3schools.com/js/js_timing.asp
unix timestamp are second from epoch (1/1/1970) so if you want to execute some code after 15 minutes just record the time when the page is loaded then every second calculate how many seconds are passed from page load. When the difference between current time and page load time is greater than 15*60*1000 you can execute your code.
var pageLoad = new Date().getTime();
function tick(){
var now = new Date().getTime();
if((now - pageLoad) > 15*60*1000) executeYourCode();
}
setInterval("tick()",1000);
Remeber that javascript return time in millisecond
Hope this helps
If the number is seconds since 1/1/1970 00:00:00, then you can convert '1792939' to a javascript date by multiplying by 1,000 and passing to Date:
var d = new Date(1792939 * 1000) // Thu Jan 22 1970 04:02:19
Currently it is about 1311428869 seconds since 1/1/1970. So if you have a value for seconds, then you can use setInterval to run a function 15 minutes after that:
var seconds = ?? // set somehow
var start = new Date(seconds * 1000);
var now = new Date();
var limit = 15 * 60 * 1000;
var lag = now - start + limit;
// Only set timeout if start was less than 15 minutes ago
if ( lag > 0 ) {
setTimeout( someFn, lag);
}
Provided the current time is less than 15 minutes from the start time, the function will run at approximately 15 minutes after the start time. If the system is busy when the time expires, the function should be run as soon as possible afterward (usually within a few ms, but maybe more).
works without server or cookie (and all browser after IE7)
Looks like you use jQuery, so you might as well use jQuery.now() insted
var firstVisit = localStorage['firstVisit'] = localStorage['firstVisit'] || $.now();
function myFunc(){
alert("I will show up 15 minutes after this pages loads!");
}
setTimeout(myFunc, parseInt(firstVisit) - $.now() + 1000 * 60 * 15);