Problem when equating date values in javascript - javascript

I'm running a bit of code that is in encased in a setInterval timer; among other things, before a certain time, it should display a "simulation starts at xxx time" message.
startdate is the time that the simulation begins, and I have defined the other variables as follows:
var d = new Date();
var da = d.getDate();
var h = d.getHours();
var mo = d.getMonth();
if ((mo != 3) || (mo == 3 && da === (startdate - 9))
|| (mo == 3 && da == (startdate - 8) && h < 21)) {
document.getElementById("infoWindow").innerHTML =
"<p style=\"color:red;\">Placeholder text</p>";
}
So, if I set startdate to (say) 10 and the month is April, I should get a message on the 1st, and the 2nd, before 9pm. But when I run the code above it skips the section in curly brackets. I have set my computer clock to ensure that the code should work eg, setting it to April 1st, and April 2nd, any time from midday to 9pm, but I get nothing.
In firefox dubugger, when I put a break point in and look at the value of "da" in the "if..." statement, it says "false" and not a numerical value. Replacing the "===" with "==" makes no difference either as I thought it was getting confused with the returned date and a true/false return from the date commands. I cannot see what is wrong.
In other parts of the code, I have other checks to make sure that the code performs things on time, such as (da==startdate+5) and they run fine, it is just this one section that is causing problems

It works fine for me, i tried startdate = 34, to make today check, then adjust my computer clock, still OK. Don't you forget any <div id="infoWindow"></div> in you html code?
var d = new Date();
var da = d.getDate();
var h = d.getHours();
var mo = d.getMonth();
var startdate = 34;
if( (mo !=3) || ( mo==3 && da===(startdate-9)) || ( mo==3 && da==(startdate-8) && h<21) ) {
document.getElementById("infoWindow").innerHTML = "<p style=\"color:red;\">Placeholder text</p>";
}
<div id="infoWindow"></div>

Related

Script to open URL only on first Friday of the month and between 8am-10am

I'm working in Virtual Tour Software with Javascript and want to make an action, which will open an URL (with photo panorama) ONLY in particular part of time (in that case it's first Friday of month and only between 8am and 10am). Any ideas? Thanks Michal
For now I got somethink like this:
var startDate = new Date('Jun 5, 2020 8:00:00').getTime();
var endDate = new Date('Jun 5, 2020 10:00:00').getTime();
setInterval(function() {
var now = new Date().getTime();
var visible = now > startDate && now < endDate;
var hotspot = this.getPanoramaOverlayByName(this.getMediaByName('Panorama'), 'Hotspot');
if(hotspot && hotspot.get('enabled') != visible)
hotspot.set('enabled', visible);
}.bind(this), 1000);`
The problem is that I need to change "var start" and "var end" every time. I want to make it visible on every First Friday of month.
you can use getday() and getdate() function in js to find the day which is friday and date which is less or equal to 7 whatever the month and year is.
you can add following in your code like this:
var d = new Date();
var startDate = d.getDate(); // this will gives you only date
var isFriday = d.getDay(); // this will gives index of the day
var n = d.getHours(); // add this new line gethours
if((startDate <= 7 && isFriday == 5) && (n >= 8 && n <= 10)) // as indexing 5 for friday
{
setInterval(function() {
var hotspot = this.getPanoramaOverlayByName(this.getMediaByName('Panorama'), 'Hotspot');
if(hotspot && hotspot.get('enabled') != true)
hotspot.set('enabled', true);
}.bind(this), 1000);
}
try this.

show/hide div during business hours, mix with UTC?

UPDATE
I have added a current working fiddle, I feel like it should be correct, but it doesn't seem to work.
https://jsfiddle.net/bill9000/yadk6sja/2/
original question:
what I have is some code to show/hide div (basically show div during certain business hours) - is there an easy way to make this use a calculate from UTC... so that the show/hide time is fixed on a certain timezone. eg. 6pm EST instead of 6pm users time... here's my current code:
var d = new Date();
var dayOfWeek = d.getDay();
var hour = d.getHours();
var mins = d.getMinutes();
var status = 'open';
if (dayOfWeek !== 6 && dayOfWeek !== 0 && hour >= 03 && hour < 15){
//if (hour=='10' && mins < '30'){
// status = 'closed';
// }else{
status = 'open';
// }
}else{
status = 'closed';
if (status=='open') {
$b('.orderby').show();
}else{
$b('.orderby').hide();
}
also, I have some other JavaScript that's getting the UTC diff:
function ShowTime() {
var now = new Date();
var diff = now.getTimezoneOffset() / 60; //the difference between local PC and UTC
diff = diff - 4; //the difference between UTC and EST
var hrs = 18-(now.getHours()+diff); //18 is the target hour
any way of making the show/hide work for the specific time?
Date() objects are already UTC, when you use d.getDay() or d.getHours(), the local timezone is applied on the fly.
You just have to use d.getUTCDay(), d.getUTCHours(), etc. to prevent this

check if "current time" is between 2 times. But also check for nights as the day before

I have 2 times for example: 10:00 and 1:00 now i want to check if current time... is between these 2 times in javascript.
The problem is that the closing time in this case is a next day so its before the openingstime. How can i do this the proper way for some reason i can not get around this.
i hav efound that this could solve it:
var start = new Date(2012,6,20,13).getTime();
var now = new Date().getTime();
var end = new Date(2012,6,21,2).getTime();
if( (start < now ) && (now < end )) {
console.log("opened");
}
else {
console.log("closed");
}
but how can i do it with 2 string formats like 10:00 and 2:00 because i do not see a option to put a time alone
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
You could use a simple function like this to convert your time to a number of minutes since 0:00:
function getMinutes(str) {
var time = str.split(':');
return time[0]*60+time[1]*1;
}
And a similar function to get the current time into the same form in order to compare:
function getMinutesNow() {
var timeNow = new Date();
return timeNow.getHours()*60+timeNow.getMinutes();
}
Then convert both opening and closing time and, if it happens that closing time is before opening time, add 24 hours to it.
var now = getMinutesNow();
var start = getMinutes('10:00');
var end = getMinutes('2:00');
if (start > end) end += getMinutes('24:00');
if ((now > start) && (now < end)) { // your code here
This is the solution I've gotten to after a bit of fiddling. At the current time of 3:24 am, it outputs the correct information. changing the now array to be [13,00] also gave the correct result of 'closed' Give it a test run through to make sure it works correctly.
Edit
jQuery included solely because I am brain dead.
Edit#2
I noticed now (9pm my time) that my conversion wasn't working, it was saying 'closed', when it shouldn't have. So far, this works for any and all numbers I've put in it to test.
var start_time = [20,00]
var end_time = [12,00]
//We've got the two start times as an array of hours/minutes values.
var dateObj = new Date(); //I just feel dirty making multiple calls to new Date().etc
var now = [dateObj.getHours(),dateObj.getMinutes()]; //Gets the current Hours/Minutes
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24; //This is something I came up with because I do a lot of math.
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
var el=$('#result');
var start_string = to_hms_string(start_time); //the start string converted to a string format. Made comparisons easier.
var end_string = to_hms_string(end_time); //See Above
var now_string = to_hms_string(now); //Above
console.log(start_string, now_string, end_string);
var status = (start_string < now_string && now_string < end_string) ? "Open" : "Closed";
el.html(status);
//Function to_hms_string stands for "hour-minute-second" string. First name that came up.
function to_hms_string(timearr){
var minutes = 60+timearr[1];
var hours = "";
if(Math.abs(timearr[0]) < 10){
hours = "0";
}
hours = (timearr[0]<0) ? "-"+hours+Math.abs(timearr[0]) : hours+timearr[0];
return hours+":"+minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
PlaceHolder
</div>
You can do this, get current time. Then define you start time and end time based on the current time getting the year, month, date for tomorrow's date add 1 to the start's date see code below. Then you can compare the time the same fi condition you have. Good luck
var now = new Date();
var start = new Date(now.getFullYear(),now.getMonth(),now.getDate(),7).getTime();
var end = new Date(now.getFullYear(),now.getMonth(),now.getDate() + 1,2).getTime();
now = now.getTime();
if( now >= start && now < end) {
console.log("opened");
}
else {
console.log("closed");
}
***EDIT**
You can convert the current time to millis after you get the year, month and date. Then use your current if condition.
Jhecht This thing right here:
if(end_time[0] < start_time[0] && now[0] < start_time[0]){
start_time[0] -= 24;
}else if(start_time[0] > end_time[0]){
end_time[0]+=24;
}
it's brilliant. It works and this is the correct answer. Great job!

If statement not running inside a setInterval

Here is the code I'm working with
var d = new Date(), // New Date object
M = d.getMonth(), // Month
D = d.getDate(), // Day of the month
h = d.getUTCHours(), // Hours in 24 hour time
m = d.getUTCMinutes(); // Minutes
console.log(M+'/'+D+' '+h+':'+m);
var href = location.href;
if(M == 1 && D == 13 && h >= 21 && m >= 17){
// It is time so lets just go there
window.location = href+'live';
}else{
// It isn't already time so lets check every 30 seconds
setInterval(checkTime, 1000)
}
function checkTime() {
if(M == 1 && D == 13 && h >= 21 && m >= 17){
// It is time so lets just go there
window.location = href+'live';
}
console.log('checked time');
}
I'm trying to check the date and time and if it's the correct date and time, forward to a different page, if it's not, then check every few seconds (every 1 second for now but I'll probably bump this up to 15 or 30) and check again and if it is now the correct date and time then forward to the new page.
The first if statement works but it doesn't seem to be running the if statement inside of the set interval function.
Maybe I just don't understand how setInterval works totally but I can't see a problem with me code.
Because you are NOT updating the variables, the values never change.
You need to do the date object check every time. They do not update.
The following
d = new Date(), // New Date object
M = d.getMonth(), // Month
D = d.getDate(), // Day of the month
h = d.getUTCHours(), // Hours in 24 hour time
m = d.getUTCMinutes(); // Minutes
needs to be in your checkTime method.

How do I change a picture during the weekends with javascript?

I want to show on our site when the chat is available. The problem is that it won't be open in the weekends. How do I exclude them? Can it be done?
<html>
<body>
<script type="text/javascript">
function chatonoff(){
var now = new Date();
var hour = now.getHours();
if (hour >=9 && hour <=18)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
</script>
<img id="chat" src="/bilder/butik/chat.png" onload="chatonoff()">
</body>
</html>
You could do like this
function chatonoff(){
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
//Check if weekend : in this case, I assume that saturday == 6 and Sunday = 0
//It depends on your location / timezone
if(day != 6 && day != 0)
{
if (hour >=9 && hour <=18)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
}
EDIT
About excluding hollidays :
You should create an array with all the off dates. Then, check if the curent day is present in the array
var offDaysListArray = ['2013-01-01','2013-01-02'];
var now = new Date();
var y = now .getFullYear();
var d = (now .getDate() < 10) ? '0'+now .getDate() : now .getDate();
var m = ((now .getMonth()+1) < 10) ? '0'+(now .getMonth()+1) : (now .getMonth()+1);
//Check if it is a closed day
if(offDaysListArray.indexOf(y + '-' + m + '-' + d) != -1)
return false; //It is a close day
Be carefull with indexOf, old browser like IE8 doesn't implement this function. Check Why doesn't indexOf work on an array IE8?
This is a very simple answer, although it won't exactly work as you want it to as JavaScript is run on the client side.
This means that someone on the other side of the world will be able to see your chat on HIS FRIDAY even though it is a SATURDAY for YOU (A Sunday/Monday example also works here). Ideally you would solve this by using some server side language such as Java / .NET / PHP or whatever you are using.
Here is your quick JavaScript fix:
<html>
<body>
<script type="text/javascript">
function chatonoff(){
var now = new Date();
var hour = now.getHours();
var day = now.getDay();
if (hour >=9 && hour <=18 && day >= 1 && day <= 5)
{
document.getElementById("chat").src = "/bilder/butik/chat-open.png";
}
}
</script>
<img id="chat" src="/bilder/butik/chat.png" onload="chatonoff()">
</body>
</html>

Categories

Resources