Pop up window on specific time - javascript

I'd like to know if there is a way to show scheduled pop up windows, say you're hosting a virtual conference at 6pm, and you want to warn your users an hour early by showing a pop up window at 5pm with a messagge like "Main conference starts in one hour".
This is for a webpage intended to work on desktop and mobile, thus I'm working on HTML and javascript.
Haven't code anything yet, I'm rather looking for a starting point.
Appreciate the help.

So based on what you just said, I think that the following js code will solve your issue, however, since I don't know what is your current environment, you will have to change the code to your needs:
// Always use a 24 hour format with this implementation.
function scheduleDailyConferences(timeArray) {
const offset = 60; // alert offset (1h prior in minutes)
const now = new Date();
const current = now.getHours() * 60 + now.getMinutes();
for (let time of timeArray) {
let tot = time.h * 60 + time.m - offset;
if (tot < current) continue;
tot -= current;
setTimeout(() => {
alert(`Your meeting starts in ${offset} minutes.`);
}, tot * 60 * 1000);
}
}
// assuming the following conferences of the day:
scheduleDailyConferences([
{ h: 13, m: 45 } // 1:45 pm
{ h: 4, m: 00 } // 4:00 pm
]);
Basically, given a time table timeArray in a human readable format, it reads every entry, subtracts a given offset of 1 hour and figures out when to fire an alert.
If the meeting has already ended or begun, it doesn't fire an alert (but you can easily change that).

Related

How to convert a string to time in javascript

I'm trying to create a countdowntimer in Javascript. There are a lof of examples on the internet. I'm trying to adjust these to my own needs. I want a countdown timer that, when started, countsdown to the whole hour. For example, if I run the code at 13:15 it wil count down to 14:00.
The problem I have is getting the time to countdown to.
var cd = new Date("Jan 5, 2021 15:37:25").getTime();
In the above example you have a defined date. I'm trying to change this to a time to the first upcoming hour. Below is what I have:
var countdowndate = newDate("cd.getMonth, cd.getYear (cd.getHour + 1):00:00").getTime();
This isn't working. What am I doing wrong here? Any help is appreciated.
Here's a very expressive way of solving this:
Get the current time stamp, floored to the last full minute.
Get how many full minutes remain until the next hour, transform to milliseconds.
Sum up the results of 1 and 2.
function getBeginningOfNextHour() {
const msPerMinute = 60 * 1000;
const currentDate = new Date();
const currentDateTimestampRoundedToMinute = Math.floor(+currentDate / msPerMinute) * msPerMinute;
const msUntilNextHour = (60 - currentDate.getMinutes()) * msPerMinute;
return new Date(currentDateTimestampRoundedToMinute + msUntilNextHour);
}
console.log(getBeginningOfNextHour());

Display a date fortnightly using javascript

This is my first time posting a question on here however I am a long term user of StackOverflow.
I am very new to Javascript and am currently trying to solve a few issues I am having on a website I am creating for my university course.
I am trying to make a little information box on the website's dashboard that simply tells you when your next rubbish bin collection day is. This is currently every 2 weeks on a Friday, the next being 1st April. I was wondering if there was a simple way for me to display the next bin collection date until it's the day of the bin collection, where the text would change to say 'bin collection today!' and after about 6pm it would change to the next collection date in a fortnight.
Sorry if this is extremely poorly worded! The website will only be used in the UK so I don't need to worry about time zones.
Any help would be very much appreciated!
Many thanks,
Emily
Below is some code to show how it might be done, hopefully there are sufficient comments.
As far as I know, some parts of the UK observe daylight saving but the following should not be affected by any change of timezone since it uses local date methods.
Any date can be used for the start of the cycle, I've chosen 10 June 2011 totally randomly. Also, any time of day can be used to change the message on the final day from "put your bins out today" to the standard "next cycle is in x days".
The algorithm is calculate the number of milliseconds to the next full fortnight from the start date by subtracting the number of milliseconds from the last full fortnight from the milliseconds per fortnight. Then the remainder is converted to full days.
To save ambiguity on the day before the cycle ends (in this case, a Thursday) the message says the cycle ends "tomorrow" rather than in 1 day, and on the day itself, up to 18:00 or 6 pm it says the cycle ends today. After that, it says the cycle ends in 14 days or less.
// Date objects are based on milliseconds (8.64e7 per day)
// Calculate milliseconds for a fortnight
var msPerFortnight = 8.64e7 * 14;
// Any date can be the start of the fortnightly cycle
// Make Friday 10 June 2011 first day of cycle,
// Cycles end on 25 March, 6 April 2016.
// Note months are zero based so June is 5
var firstDayOfCycle = new Date(2011, 5, 10);
// Time of day to stop showing "put bins out today" message on start/end day
// 18 is 6 pm
var endHour = 18;
// Get the day name for the cycle start/end
var dayName = ['Sunday','Monday','Tuesday','Wednesday','Thursday',
'Friday','Saturday'][firstDayOfCycle.getDay()];
// Convert end hour to convenient format with am/pm
var endHourNeat = (endHour % 12 || 12) + ' ' + (endHour < 12? 'am' : 'pm');
// Get a date for now
var now = new Date();
// Get milliseconds to next full fortnight by
// msPerFortnight minus milliseconds since last full fortnight
var m = msPerFortnight - ((new Date() - firstDayOfCycle) % msPerFortnight);
// Calculate time remaining full days
var daysLeft = Math.ceil(m / 8.64e7);
// Create a human friendly message
var message;
// If more then one day left, or after 18:00 on last day, show this message
if (daysLeft == 14 && now.getHours() < endHour) {
message = 'Today is ' + dayName + ', so please put your bins out before ' + endHourNeat + '!';
} else if (daysLeft > 1 ) {
message = 'Put your bins out on ' + dayName + ' in ' + daysLeft +
' day' + (daysLeft == 1?'':'s') + ' time.';
} else if (daysLeft == 1) {
message = 'Put your bins out tomorrow, on ' + dayName + '.';
}
document.write(message);
You can even add the date of the end of the cycle and add ordinal, so it might read "Put your bins out on Friday the 25th, in 3 days time". But I'll leave that up to you.
A possible solution is to use Unix epoch, because they give you your time in seconds from 1/1/1970. By using this we can find how far we are into a fortnight. I found that Math.floor(Date.parse("2016-04-01")/86400000)%14equals 8.
Then your code might be:
var days_into_fortnight=Math.floor(Date.now()/86400000)%14;
var string_to_show;
var days_to_collection;
if (days_into_fortnight==8){
string_to_show="Bin collection!";
}
else{
if(days_into_fortnight<8){
days_to_collection=8-days_into_fortnight;
}
else{
days_to_collection=22-days_into_fortnight;
}
string_to_show=days_to_collection.toString()+" day(s) to collection!";
}
Edit:spelling

How to get a countdown timer that starts on a specific date/time and counts down every hour

I'm trying to achieve a countdown timer that would use a specific date and time for it to start. From there I need it to countdown from 1 hour and then update the initial date and time by adding an hour and then repeat itself indefinitely.
This is used for a product auction that would get a new product once one sells out and the price drops every hour from when it is added to the auction which could be any time of day.
Example:
I need this timer to start on 2014, 7, 25, 11, 30, 0, 0 (August 25th,
2014 at 11:30 AM EST) It would countdown 1 hour and upon completion it
would add on an hour to the start date making 2014, 7, 25, 12, 30, 0,
0 This would repeat itself indefinitely until I choose to stop it.
It would also not change based on if the site visitor refreshed the page, meaning they visit the page and see 33 minutes left, not keep resetting it to 1 hour for each refresh.
I was going to use this countdown timer: http://keith-wood.name/countdown.html
What I needed was the time that I give it in variable form. I tried to research this as much as possible without any luck, most are not specific enough or only deal with the date and not the time.
I'm not that well versed in Javascript and jQuery; here is what I had so far.
Pardon my code, there are many ideas at work here:
$(document).ready(function() {
var everyhour = new Date();
//everyhour = new Date(everyhour.getFullYear() + 1, 1 - 1, 1);
everyhour = 2014, 8-1, 25, 9, 30, 0, 0;
// the above was my initial try and it wasn't getting me anywhere
var date = new Date(2014, 7, 25, 12, 0, 0);
var now = new Date();
var diff = date.getTime()/1000 - now.getTime()/1000;
alert (diff);
// The above was another stab at it, got me a little closer
var minutesToAdd = 60;
date.setMinutes(date.getMinutes()+minutesToAdd);
// the above was something I found on this website and got brain block
// the below was me trying to start a loop and get the date to update by adding an hour onto it
// for i
// if diff = 3600 {
// var dated = dated + 1
// }
$('#auctioncountdown').countdown({until: diff, format: 'HMS'});
});
Any help would be greatly appreciated.
You can use setInterval to continuously update the countdown:
setInterval(function(){
// update countdown
}, 1000 * 60); // for every hour
setInterval will cause the function you pass in to run continuously every hour (in this case).
I ended up going with something simpler and ultimately achieving what I was originally asking, using 'now' instead of a specific date. Having a timer reset itself every hour and refreshing the page to changed content. In my case I'm actually adding a couple of minutes to the time because of a background app taking a minute or two to do it's communication on updating the server with new information. It's basically to get rid of the lag time and make a better user experience for the page visitor.
Here is my code:
$(document).ready(function() {
function ShowTime() {
var now = new Date();
var diff = -2;
var nowTwo = new Date(now.getTime() + diff*60000);
var mins = 59-nowTwo.getMinutes();
var secs = 59-nowTwo.getSeconds();
timeLeft = "" +mins+'m '+secs+'s';
$("#auctioncountdown").html(timeLeft);
if ($("#auctioncountdown").html() === "0m 1s") {
location.reload(true)
};
};
function StopTime() {
clearInterval(countdown);
}
ShowTime();
var countdown = setInterval(ShowTime ,1000);
});

Javascript between Two Times

I'm currently trying to create a JavaScript which will display on our website when our shop is open, and when it is closed.
I basically want to create an if statement between two times, these being 8:30 and 5:30.
I'm currently doing the following, although it won't work as I effectively have two lots of 'minutes' defined which cancel each other out.
<script type="text/javascript">
var Digital=new Date();
var day=Digital.getDay();
var hours=Digital.getHours();
var minutes=Digital.getMinutes();
// Monday - Open //
if (day==1 && hours>=8 && minutes>=30 && day==1 && hours<=17 && minutes<=30)
document.write('Open today until 5:30pm');
</script>
Can anyone suggest a way of achieving what I am trying to do?
How about this:
if(day == 1 && hours*60+minutes >= 510 && hours*60+minutes <= 1050) {
// do stuff
}
With 8 * 60 + 30 = 510 and 17 * 60 + 30 = 1050.
One thing to note here is
new Date()
gets the local time from the client's clock. If the client's clock is set at a different time zone you might not get the result you are hoping for.
I would suggest getting the client's timezone as well and converting that to your desired timezone adding/subtracting any offset, start with something like
var clientTime = new Date();
var clientTimeZone = clientTime.getTimezoneOffset();
//getTimezoneOffset returns the time-zone offset in minutes between the current locale and UTC.

Subdividing and Isolating Time with javascript

I am making a website for a limo service that should provide the price for the service you are requesting beforehand.
The regular service is 1$ a minute. However, all the time from mid-night to 8am, is considered premium and it costs 2$.
Now, here is the complicated part. I need to isolate how much time the client is paying on regular time and on premium, in order to generate the price.
For example. If the service is from 9pm to 2am, the client pays 3 hours at 1$/min and 2 hours at 2$/min.
How to I get the 9pm and 2am, and convert to 180minutes+120minutes?
Btw, I tied tampering with http://code.google.com/p/datejs/. But it just was not working. Is there a smart "math" way of doing this?
Thanks for the help guys :)
So premium time is all in the A.M. it seems and non is all in the P.M. so just subtract whatever time they give that's pm from 12, in your example 12-9 and you get 3hours, then add any hours to 0 for the am, again your example 0+2 which is of course 2 hours. Then times by 60 to get the minutes. Once you have that times each amount by the amount its being charged and add them together. I would have the am/pm be a toggle that sets a variable to true/false for each.
code could look something like this:
//start_time and end_time are objects that have 2 properties, am/pm
//which is a bool and time which is a int
function calc_time(start_time,end_time){
var normal_pay;
var premium_pay;
if(start_time.pm == true){
normal_pay = 12 - start_time.time;
normal_pay = normal_pay * 60;
} else{
normal_pay = 0 + start_time.time;
normal_pay = normal_pay * 60 * 2; //this is premium time the whole night was premium pay
}
if(end_time.am == true){
premium_pay = 0 + end_time.time;
premium_pay = premium_pay * 60 * 2;
} else {
premium_pay = 12 - end_time.time;
premium_pay = premium_pay * 60; //this is normal time the whole night was normal pay
}
return premium_pay + normal_pay;
}
This doesn't solve everything you still have to account for things like minutes, say they want to end at 3:25am but that's not that hard.

Categories

Resources