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>
Related
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>
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.
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
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/
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);