How to refresh a page in a certain month. JS - javascript

I have a function that refreshes my page at a specific time and day but how can I refresh only on a specific month and date at a certain time? The reason why I want to do this is because my website checks for updates on football transfers that only takes place on specific months.
Here is my function to refresh certain time in a day
function refreshAt(hours, minutes, seconds, day) {
var now = new Date();
var then = new Date();
var dayUTC = new Date();
if(dayUTC.getUTCDay() == day) {
if(now.getUTCHours() > hours ||
(now.getUTCHours() == hours && now.getUTCMinutes() > minutes) ||
now.getUTCHours() == hours && now.getUTCMinutes() == minutes && now.getUTCSeconds() >= seconds) {
then.setUTCDate(now.getUTCDate() + 1);
}
then.setUTCHours(hours);
then.setUTCMinutes(minutes);
then.setUTCSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
}

I've cleaned up your code a bit, and added in a line that would also let you set a specific date and month:
function refreshAt(hours, minutes, seconds, day, month) { // added month argument
var now = new Date();
var then = new Date( // used format: new Date(Y, M, D, h, m, s);
now.getUTCFullYear(),
month!=undefined ? month : now.getUTCMonth(),
day,
hours,
minutes,
seconds
); // fill in the date when defining the variable
// You don't need a seperate Date object to get the UTC date
if (now.getUTCDate() == day && (month == undefined || now.getUTCMonth() == month)) {
if(now.getTime() > then.getTime()) {
then.setUTCDate(now.getUTCDate() + 1);
}
// exit function if the new time is still after the current time
if (now.getTime() > then.getTime()) return;
// you don't need brackets around this
var timeout = then.getTime() - now.getTime();
setTimeout(function() { window.location.reload(true); }, timeout);
}
}
I hope the comments make clear what modifications I made. If anything is still unclear, please leave a comment to this answer.
The line of month!=undefined ? month : now.getUTCMonth(), does the following:
If the month is not undefined, then fill in the month, and if it is not filled in, then use the current month. This means that using the following syntax would still work:
refreshAt(23, 59, 59, 30); //refreshes at 23:59:59 UTC today (30 Jan 2014)
Date as parameter
You can also make this a bit easier by just supplying a Date object as a parameter, instead of each individual variable. That would look something like this:
function refreshAt(date) { // added month argument
var now = new Date();
if (now.getUTCDate() == date.getUTCDate()) {
var timeout = date.getTime() - now.getTime();
if (timeout > 0)
setTimeout(function() { window.location.reload(true); }, timeout);
}
}
This can then be called via
refreshAt(new Date(2014, 0, 30, 23, 59, 59));
This sets a refresh timer for 30 Jan 2014, 23:59:59 UTC.

Related

Can I use comparison and logical operators for time inputs in Javascript? [duplicate]

I'm trying to write a statement that says "if time is this and less than that then". I can use get hours and get min. However, I'm having problems combining a time such as 9:30.
Example,
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var mintues = now.getMinutes();
if (day == 0 && hour >= 9 && hour <= 11 && mintues >= 30) {
document.write(now);
}
This only if the time is less between 9:30 10. As soon as the clock hits 10 the minutes are then < 30 and the script breaks.
Any thoughts on how to better incorporate the time function to make this theory work?
Thanks,
use new Date().getTime() returns milliseconds for much easier comparison. This way there is no need to check hour, min, second, millisecond. Fiddle link
var d930 = new Date(2010, 12, 21, 9, 30, 0, 0), // today 9:30:00:000
d931 = new Date(2010, 12, 21, 9, 31, 0, 0), // today 9:31:00:000
t930 = d930.getTime(),
t931 = d931.getTime();
console.log(t931 > t930);
This way your code can check against a static 9:30 time.
var time930 = new Date(2010, 12, 21, 9, 30, 0, 0).getTime(),
sunday = 0,
now = new Date();
if(now.getDay() == sunday && now.getTime() >= time930){
/* do stuff */
}
You have a few typos and basic javascript errors.
Might wanna brush up on the basics.
W3Schools is where I learned all I know.
It works fine if you fix them...
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
var minutes = now.getMinutes();
if(day == 0 && hour == 9 && minutes < 30 && minutes > 10 || day == 0 && hour == 9)
document.write('Time is between 9:10 and 9:30');
Think of the if statement as basic logic.
If the day is Sunday(0)
AND the hour is 9
AND the minutes are greater than 10
AND the minutes are less than 10
OR the day is Sunday(0)
AND the hour is before 9.
var now = new Date();
var closeTime = new Date();
closeTime.setHours(9); closeTime.setMinutes(30);
console.log(now, closeTime, now.getTime() >= closeTime.getTime());
close time is based on today, then we just change the hours and minutes to 9:30.
I made this solution simple and easy to read (thus easy to adjust).
// we need a function that makes hours and minutes a two digit number
Object.prototype.twoDigits = function () {
return ("0" + this).slice(-2);
}
// get current date and time
let now = new Date();
// compile the current hour and minutes in the format 09:35
timeOfDay = now.getHours().twoDigits() + ':' + now.getMinutes().twoDigits();
// test if timeOfDay is within a given time frame
if ('09:30' <= timeOfDay && timeOfDay <= '11:30') {
console.log('inside time frame');
} else {
console.log('outside time frame');
}
I had a similar problem to solve today, I setup a little component that returns if a place of business is open or not. Got the time by dividing the minutes by 100 then adding it to the hours. So 8:30 is represented as 8.3
let d = new Date()
let day = d.getDay()
let hours = d.getHours()
let minutes = d.getMinutes() / 100
let time = hours + minutes
if (day == 1) {
if (time > 8.3 && time < 17.3) {
setIsOpen(true)
} else {
setIsOpen(false)
}
}
if the hour is less than 9, true
or
if hour is 9 and minutes lt 30, true
so that would look like
if ((hour < 9) || (hour == 9 && minutes < 30))
Use words to figure out your logic. Symbols are just shortcuts.
One way is to do a direct comparison on date objects. Choose an arbitrary year, month and day, and then incorporate your times as follows:
var older = new Date("1980-01-01 12:15");
var newer = new Date("1980-01-01 12:30");
if (newer > older){
alert("Newer time is newer");
} else {
alert ("The time is not newer");
}
The MDC documentation on the Date object will help with some more details. The bottom line is that if you want to compare times, you don't actually need to call any methods on the objects, and it's possible to directly compare them. The date() object can take a variety of strings to assign a new time to the returned instance, these are from the MDC documentation:
today = new Date();
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
As you can see, it's pretty simple. Don't complicate, and have a look through the documentation :)
While we're here, here's a test using your example:
var base = new Date("1980-01-01 9:30");
var test = new Date("1980-01-01 9:30:01");
if (test >= base){
alert("test time is newer or equal to base time");
} else {
alert ("test time is older than 9.30");
}
Try this:
var now = new Date();
var hour = now.getHours();
var mintues = now.getMinutes();
if(
(hour*60 + mintues) > 570 &&
hour <= 11
)
{
document.write(now);
}
I don't quite fully understand your question but hope this helps.
c = new Date();
nhour = c.getHours();
nmin = c.getMinutes();
if(nmin <= 9) {
nmin = "0" + nmin;
}
if(nhour <= 9) {
nhour = "0" + nhour;
}
newtime = nhour + "" + nmin;
if(newtime <= 0930){
alert("It is before 9:30am or earlier");
}

Add timezone to this js schedule?

I have this javascript code to schedule when certain divs show, but the problem I'm having is it's not using device time or our time zone. I really need it to be assigned to the central time zone.
function displayMsg() {
var currentTime = new Date();
function toUTC(date) {
return Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
date.getMilliseconds()
);
}
toUTC(currentTime);
var startMsg1Time = new Date("2021-10-03T11:15:00Z");
var endMsg1Time = new Date("2021-10-08T14:33:00Z");
var startMsg2Time = new Date("2021-11-15T23:00:01Z");
var endMsg2Time = new Date("2021-11-16T22:59:59Z");
if (currentTime.getTime() > startMsg1Time.getTime() && currentTime.getTime() <= endMsg1Time.getTime()) {
$('.Msg1').show();
} else if (currentTime.getTime() > endMsg1Time.getTime) {
$('.Msg1').hide();
}
if (currentTime.getTime() > startMsg2Time.getTime() && currentTime.getTime() <= endMsg2Time.getTime()) {
$('.Msg2').show();
} else if (currentTime.getTime() > endMsg2Time.getTime) {
$('.Msg2').hide();
}
}
displayMsg();
As a side note, this isn't completely achieving what I need. I'm trying to have a message show every Sunday from 8:30am-11:15am and Friday from 7:00pm-8:15pm. I was going to use this method and just create a schedule a month at a time, but if anyone can recommend a better approach then I'm happy to hear.
You can do something like in below snippet , i.e , giving only minutes and hour and then checking if day = 1 (Monday) . I have set alarm time to 11:25 PM to 11:35 PM(Monday) (You can set any)
Use update of alarm according to need , here I have set 1sec using setInterval
Below snippet is for demo only , you can have any number of messages and alarm and specify day of alarm to come up or month (and can be year to which alarm ring)
setInterval(function() {
var d = new Date();
var Msg1Day = d.getDay();
var Msg1TimeStart = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 25, 0, 0)
var Msg1TimeEnd = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 35, 0, 0)
if (Msg1Day === 1) {
if (d >= Msg1TimeStart && d <= Msg1TimeEnd) {
document.querySelector("#demo").innerHTML = "Alarm is ON"
document.querySelector(".Msg1").innerHTML = "You already enjoyed Sunday, It's Monday Time and soon will Be Tuesday(Alarm is from 11:25 PM - 11:35 PM)"
} else {
document.querySelector("#demo").innerHTML = "Alarm is OFF"
document.querySelector(".Msg1").innerHTML = ""
}
} else {
document.querySelector("#demo").innerHTML = "Today is not monday"
}
}, 1000);
<div class="Msg1"></div>
<div id="demo">Alaram status will be in 1sec and will be updated every second</div>

Building a business hours with javascript

I been trying to display "Currently opened on Monday - Friday." & going to change to "Currently closed on Saturday - Sunday."
I try to learned by googling but I was not able to achieve:
window.onload = function status() {
var date = new Date();
console.log(date);
//var day = date.getDay();
var hour = date.getHours();// 0 = 12am, 1 = 1am, ... 18 = 6pm\
console.log(hour);
// check if it's between 9am and 11pm
if(hour > 12 ) {
document.getElementById('example').innerHTML = "Currently opened on Monday - Friday.";
} else if (hour < 23 ) {
document.getElementById('example').innerHTML = "Currently closed on Saturday - Sunday.";
} else {
console.log('Today is not a weekend and hour is between 12 - 23')
}
};
setInterval(status, 1000);
console.log(status);
you can use the getDay() method of the Date object to get the day of the week, then you check if it is a day of the week where its opened or not, if its opened then you check the hours.
function status() {
var date = new Date();
var day = date.getDay();
var hour = date.getHours();
//check if its sunday or saturday
if (day == 0 || day == 6) {
document.getElementById('example').innerHTML = "Currently closed on Saturday - Sunday.";
// check if its between 9am and 11pm (inclusive)
} else if (hour >= 9 && hour <= 23) {
document.getElementById('example').innerHTML = "Currently opened on Monday - Friday.";
} else {
console.log('Today is not a weekend and hour is between 12 - 23')
}
}
check working example https://jsfiddle.net/93ut5jve/9/
references:
https://www.w3schools.com/jsref/jsref_getday.asp (get day function)
Here is a simple solution that could help to point you in the right direction.
I think that one of the problems with your code is that it only captured the hour of the day, and not the day of the week.
Below you can set your open days and hours in the open object, but if you have different open times on different days in the future, you will need to define the open object differently and will have to change how the getStatus function works
// set up the interval so that the time can be started and stopped as needed
var interval;
// set the days and times when open (this could be set up differently, for example it could be a range instead)
var open = {
days: [1, 2, 3, 4, 5],
hours: [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
}
// given a date, return a message determining if open
var getStatus = function(currentDate){
var hour = currentDate.getHours();
var day = currentDate.getDay();
var nowIsOpenDay = open.days.indexOf(day) > -1;
var nowIsOpenHour = open.hours.indexOf(hour) > -1;
var message = (nowIsOpenDay && nowIsOpenHour) ? 'Currently opened' : 'Currently closed';
return {
'message': message,
'dateInfo': {
'hour': hour,
'day': day,
'nowIsOpenDay': nowIsOpenDay,
'nowIsOpenHour': nowIsOpenHour
}
}
}
// run the timer and get the current status
var startInterval = function(updateInterval){
updateInterval = (typeof updateInterval === 'undefined') ? 1000 : updateInterval;
interval = setInterval(function(){
var currentStatus = getStatus(new Date());
console.log(currentStatus.message)
console.log(currentStatus.dateInfo.hour, currentStatus.dateInfo.day)
}, updateInterval);
}
// optionall stop the interval
var stopInterval = function(){
clearInterval(interval);
}
// start
startInterval(2000);

Automatically load new HTML page at given time

I would like my homepage to change each day at a specific time (1pm).
The page has a 24hr countdown timer and when it reaches zero, I would like a new page to load and the timer starts again.
I understand how to make a page refresh after a particular time
<script>
setTimeout(function(){
window.location='Page2.html';
}, 5000);
</script>
But not how to make this happen at a particular time of the day (1pm).
You can try using a getting the current time on page load/refresh. Then calc the milliseconds until 1pm. And use that to set your setTimeout. I suggest using a library like moment to do time calculations.
Load moments in your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
In JS:
// time right now
var now = moment.now();
// set refresh hour to 1pm
var nextRefresh = moment.now().hour(13).minute(0).second(0).millisecond(0);
// check if is or after 1pm
if (now.hour >= 13) {
nextRefresh.add(1, 'days'); // add 1 day
}
setTimeout(function() {
console.log('next 1pm');
}, nextRefresh.diff(now));
And #Stoycho Trenchev is right. You will probably want to call setInterval with 86400000 ms in the setTimeout. This way, your page will refresh everyday afterwards.
You need setInterval not setTimeout and you need to calculate 24h in milliseconds :)
Here you go just a fyi JavaScript uses the browsers time so just because it's 1pm where you are it won't be 1pm where the user is.
var intervalId = window.setInterval(checkTime, 500);
function checkTime() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(h == 13 && m == 0 && s == 0) return window.location='Page2.html';
}
Ah. Something like?
<script>
function getTime() {
var date = new Date()
var time = date.getTime();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var time = {'hours': hours, 'minutes': minutes, 'seconds': seconds};
}
setInterval(function() {
var time = getTime();
if (time.hours === 13 && time.minutes === 0) {
window.location = 'Page2.html';
}
}, 500);
</script>
You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

checking if a current time falls in a particular interval in javascript

EDIT: Please take care to introduce UTC timing in your answer. Since doing things on client side will lead to different time zones.
In javascript, i can get the current time, hour and minute as follows:
var currentTime = new Date();
var currentHour = currentTime.getHours();
var currentMinute = currentTime.getMinutes();
Now i have to perform a task only if the current time false in an interval with a fixed time.
Say there is a fixed time 10:30 AM. Users can perform a certain task iff the current time, is 4 hours behind the current time or 1 hour ahead of the fixed time.
meaning users can perform the task from 6:30 AM to 11:30 AM.
I tried getting the current hours and doing
start = fixed_time - 4;
end = fixed_time + 1;
if currentHour< end or currentHour > start{
do some stuff;
}
But this ignores the minutes, how to take care of that?
Otherwise, how could i figure if the current time lies between 6:30 AM and 11:30 AM?
var currentTime = new Date();
var startTime = new Date(2012, 3, 8, 6, 30, 0, 0); //6:30am today
var endTime = new Date(2012, 3, 8, 11, 30, 0, 0); //11:30am today
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
If you need it to be more dynamic you can
var currentTime = new Date();
var startTime = new Date();
startTime.setHours(6);
startTime.setMinutes(30);
var endTime = new Date();
endTime.setHours(11);
endTime.setMinutes(30);
if ((currentTime.getTime() > startTime.getTime()) && (currentTime.getTime() < endTime.getTime())
{
//current time is between start and end so do what you need to do
}
You can use getTime() method which returns the number of milliseconds since midnight Jan 1, 1970:
currentTime = (new Date()).getTime();
Then all you need is to calculate the difference between your fixed time and current time in milliseconds. 4 hours equals to 14,400,000 (4*60*60*1000) milliseconds.
You can compare dates to one another. So, using the current date and time you can compare that to dates with a fixed time set. Something like:
var now = new Date
,lower = new Date
,upper = new Date;
//determine limits
lower.setHours(6);
lower.setMinutes(30);
upper.setMinutes(30);
upper.setHours(11);
//tests
now = new Date('2012/04/08 22:00');
console.log(now >= lower && now <= upper); //=> false
now = new Date('2012/04/08 07:00');
console.log(now >= lower && now <= upper); //=> true
var startTime = '01 AM'; // or var startTime = '01:00 AM';
var endTime = '09 AM'; // or var startTime = '09:00 AM';
var now = new Date();
if(now < convert_time(endTime) && now > convert_time(startTime)){
alert("With in a range");
}else{
alert("Out of range");
}
function convert_actual_time(time) {
if(time.indexOf(" ") != -1){
split1 = time.split(" ");
splitTime = split1[0];
splitZone = split1[1];
}
if(splitTime.indexOf(":") != -1){
split2 = splitTime.split(":");
setHours = split2[0];
setMins = split2[1];
}else{
setHours = splitTime;
setMins = "00";
}
if(splitZone.toLowerCase() == "pm"){
setHours = parseInt(setHours)+12;
}
date = new Date();
date.setHours(setHours);
date.setMinutes(setMins);
return date;
}
Try with this code

Categories