How to compare opening hours? - javascript

I want to compare opening hours stored on my server with the current time.
Given the following:
start: 09.00
end: 00.30
I want the result if the store is open or closed. When the current time isn't in the given start and end time the store is closed.
The code i use until now does not work. I get the error:
TypeError: Cannot read property '3' of undefined
firebase.database().ref("v3/standalonelist/bars").on('value', function(snapshot) {
$timeout(function() {
$scope.content = snapshot.val();
snapshot.forEach(function(childSnapshot) {
$scope.data1 = [childSnapshot.val()];
$scope.locations1 = $scope.data1
$scope.locations1.forEach(function(item) {
$scope.getMinutes = function(str) {
var time = str.split('.');
return time[0] * 60 + time[1] * 1;
}
$scope.getMinutesNow = function() {
var timeNow = new Date();
return timeNow.getHours() * 60 + timeNow.getMinutes();
}
var a = new Date();
var day = a.getDay(); // 3
var now = $scope.getMinutesNow();
console.log(item.opens[day]); // returns 09.00
var start = $scope.getMinutes(item.opens[day]); // 09.00
var end = $scope.getMinutes(item.closes[day]); // 01.20
if (start > end) {
end += $scope.getMinutes('24.00');
}
if ((now > start) && (now < end)) {
$scope.$apply(function() {
$scope.open = true; // Store is open
})
} else {
$scope.open = false; // Store is closed
}
})
})

I think you are making it a little more complicated than it has to be...
var today = new Date(),
open = "Open",
closed = "Closed",
display = document.getElementById('display'),
start = new Date(), end = new Date();
// Set the opening hour:minutes
start.setHours(10);
start.setMinutes(5);
// Set the closing hour:minutes
end.setHours(18);
end.setMinutes(30);
// Check the time based on milliseconds
if (
today.getTime() >= start.getTime() &&
today.getTime() < end.getTime()
) {
display.innerHTML = open;
} else {
display.innerHTML = closed;
}
Here is a working fiddle: http://jsfiddle.net/L770r2qk/
You might also want to take into account different days, such as a business that runs from late night to early morning. For that you would also want to use start.setDate(12) and end.setDate(13). You then might also want to take into account month changes where you would then use start.setMonth(10) and end.setMonth(11).
Those extra features are up to you and I will let you implement them into the example.

Related

How to get value of time from a column, extend the duration, and then create event on google calendar?

OBJECTIVE
Create event on calendar depending on submitted date time and duration
Problem
Retrieving value of time from a column,
Extend the duration of the booked time depending on submitted duration
Create event based on the duration
My Code
var dateCol = 3; ////this column retrieve DATE from google form
var timeCol = 4; //this column retrieve TIME from google form
var durCol = 5; ////this column retrieve STRING from google form
var serviceCol = 6;
var eventIDCol = 21;
var appCol = 23
var revCol = 24;
var response = e.range;
var rRow = response.getRow()
var resprange = responsesheet.getRange(rLR,1,1,rLC);
var respdata = resprange.getValues();
copysheet.appendRow(respdata[0]);
var eventTitle = copysheet.getRange(rRow,serviceCol).getValue();
var startDate = copysheet.getRange(rRow,dateCol).getValue();
var startTime = copysheet.getRange(rRow,timeCol).getValue();
startDate.getTime().setHours(startTime.getHours());
startDate.getTime().setHours(startTime.getMinutes());
var endTime = new Date(startDate);
var duration = copysheet.getRange(rRow,durCol).getValue();
if (duration == 'Less than 45 minutes') {
endTime.setMinutes(startDate.getTime().getMinutes()+45);
} else if (duration == 'Less than 1 hour') {
endTime.setMinutes(startDate.getTime().getMinutes()+60);
} else if (duration == 'Less than 2 hours') {
endTime.setMinutes(startDate.getTime().getMinutes()+120);
} else {
endTime.setMinutes(startDate.getTime().getMinutes()+180);
};
var conflicts = calendar.getEvents(new Date(startDate), new Date(endTime));
if (conflicts.length < 1) {
var event = calendar.createEvent(eventTitle, new Date(startDate), new Date(endTime));
var eventID = event.getId().split('#')[0];
copysheet.getRange(rRow,appCol).setValue("approve");
copysheet.getRange(rRow,eventIDCol).setValue(eventID);
} else {
copysheet.getRange(rRow,appCol).setValue("conflict");
}
NOTE: I am sure that the problem is with retrieving the time value and adding minutes part. Should I convert time value to string first? Any help is greatly appreciated
Yes, it was a super silly mistake, thank you #James for the hint. I simply got rid of getTime() and it works perfect. This is the code:
startDate.setHours(startTime.getHours());
startDate.setHours(startTime.getMinutes());
var endTime = new Date(startDate);
var duration = copysheet.getRange(rRow,durCol).getValue();
if (duration == 'Less than 45 minutes') {
endTime.setMinutes(startDate.getMinutes()+45);
} else if (duration == 'Less than 1 hour') {
endTime.setMinutes(startDate.getMinutes()+60);
} else if (duration == 'Less than 2 hours') {
endTime.setMinutes(startDate.getMinutes()+120);
} else {
endTime.setMinutes(startDate.getMinutes()+180);
};
Notice that after value of time has been retrieved, no need to use getTime() anymore.

Can I define an object's properties using self-referential functions in Javascript?

I'm trying to determine four dates based on the current date -- the beginning of the current pay period to today, and then then start and end dates of the previous pay period -- and I'm having trouble finding the correct execution.
To me it makes sense to have an object with four properties like payPd.currentStart, payPd.currentEnd, payPd.priorStart, and payPd.priorEnd.
Currently I'm working backward from the .currentEnd, which is today, and subtracting days until it's Monday on an odd week -- pay periods are two weeks long:
var dt = new Date();
Date.prototype.getWeek = function () {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
var currentStart = '';
var currentEnd = new Date();
var priorStart = '';
var priorEnd = '';
function ppdStart(currentEnd){
var inDate = currentEnd;
while (inDate.getWeek() % 2 !== 0 || inDate.getDay() !== 1) {
inDate.setDate(inDate.getDate() - 1);
}
return outDate;
}
So the question is, can I define one property, then define the next property as a function of that one (next odd Monday before today), and so on with the rest? Would I want a callback function, or a get/set? I'm not sure where to go next.
Thanks to all of you in the Javascript community I'm just now joining.
I personally wouldn't bother with extending the prototype for such function. You might as well have a wrapper around a date object that handles any calculation based on the date you originally send in.
This date could then be used to get to the next or the previous period relative to the original date.
I added a snippet of what I mean, and it gives you an easy way to determine the date you originally asked for, and it's pay date. The end period for the payment would then be the start date of the next period minus 1 day.
// from: https://stackoverflow.com/a/7751977/3231537
const twoWeeks = 12096e5;
// from: https://gist.github.com/dblock/1081513
var weekOfYear = function(date){
var d = new Date(+date);
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
};
class PayDateHelper {
constructor( date ) {
this._date = date;
}
nextPayPeriod() {
return new PayDateHelper( new Date( this.currentDate.getTime() + twoWeeks ) );
}
previousPayPeriod() {
return new PayDateHelper( new Date( this.currentDate.getTime() - twoWeeks ) );
}
get currentDate() {
return this._date;
}
get payDate() {
let interval = 0;
// when we are in an even week, subtract 7 days
if ( weekOfYear( this.currentDate ) % 2 === 0 ) {
interval += 7;
}
// and substract the days of the week back to 1 (monday)
interval += (this.currentDate.getDay() - 1);
const date = new Date( this.currentDate );
date.setDate( date.getDate() - interval );
return date;
}
}
console.log('-- current period');
let helper = new PayDateHelper( new Date() );
console.log( helper.currentDate );
console.log( helper.payDate );
console.log('-- next period');
let nextPeriod = helper.nextPayPeriod();
console.log( nextPeriod.currentDate );
console.log( nextPeriod.payDate );
console.log('-- previous period');
let previousPeriod = helper.previousPayPeriod();
console.log( previousPeriod.currentDate );
console.log( previousPeriod.payDate );
It seems that you want to do something like (in pseudo code):
let obj = {
today: new Date(),
yesterday: today - 1 day,
tomorrow: today + 1 day
};
where you set today to whatever value and yesterday and today are updated accordingly.
You can do that with a getter, so that getting the values for yesterday and tomorrow calculates them based on the value for today.
e.g.
let obj = {
get yesterday() {
if (this.today != undefined) {
let d = new Date(this.today);
d.setDate(d.getDate() - 1);
return d;
} else {
return void 0;
}
},
get tomorrow() {
if (this.today != undefined) {
let d = new Date(this.today);
d.setDate(d.getDate() + 1);
return d;
} else {
return void 0;
}
}
};
// Initial values
console.log('Yesterday: ' + obj.yesterday)
console.log('Today : ' + obj.today)
console.log('Tomorrow : ' + obj.tomorrow)
// Set today
obj.today = new Date();
// Get values
console.log('Yesterday: ' + obj.yesterday.toDateString());
console.log('Today : ' + obj.today.toDateString());
console.log('Tomrrow : ' + obj.tomorrow.toDateString());

How to set an element to show only for a certain period of time in Wix using JavaScript?

There is a chatbox button in my Wix website. I want the chatbox to appear only during the days and times I written in a dataset. For example, This is the image of the dataset example. What I am trying to do with the dataset is that the chatbox will appear every Saturday from 7p.m. to 9p.m. How can I set the chatbox to appear only during those times with Javascript Date API.
My current code is :
var day;
wixData.get("ScheduleTable", "day").then((results) => {
day = results;
})
.catch((err) => {
let errorMSg= err;
})
//StartTime
var startTime;
wixData.get("ScheduleTable", "startTime").then((results) => {
startTime = results;
})
.catch((err) => {
let errorMSg= err;
})
//endTime
var endTime;
wixData.get("ScheduleTable", "endTime").then((results) => {
endTime = results;
})
.catch((err) => {
let errorMSg= err;
})
$w.onReady(function () {
//TODO: write your page related code here...
var startD = new Date(Date.UTC(2019,10,day,startTime));
var endD = new Date(Date.UTC(2019,10,day,endTime));
var today = new Date();
if(today >= startD || today <= endD) {
$w('#wixChat1').show();
} else {
$w('#wixChat1').hide();
}
});
Why do you need to create a database for only 1 field? Just hard code the time on the page.
Hide the Wix Chat App by default using the properties panel.
$w.onReady(function () {
var date = new Date();
var day = date.getDay(); //Saturday is 6
var time = date.getHours(); //7 pm is 19 & 9 pm is 21
console.log({day,time}); //console to check day and current hour
if(day === 6 && time >= 19 && time <= 21) {
$w("#wixChat1").show();
}
});
If you are adamant on querying the database then perform a query like below.
//---------------------Query
import wixData from 'wix-data';
$w.onReady(function () {
getData();
});
function getData() {
wixData.query('ScheduleTable') //database id
.find()
.then( (results) => {
let Item = results.items[0]; //this returns the first item found in the database
let start = Item.startTime; //this HAS to be a number and in 24 hr format
let end = Item.endTime; //same as above
decide(start, end);
});
}
function decide(start, end) {
var date = new Date();
var day = date.getDay();
var time = date.getHours();
if(day === 6 && time >= start && time <= end) {
$w("#wixChat1").show();
}
}

Custom code to display current time not working

//<![CDATA[
var displayCurrentTime = new function() {
// Get values...
var sysHour = getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins: getMinutes; // Get current minutes...
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function() {
displayCurrentTime();
}, 1000);
//]]>
I've been reading up some information and I wanted to create a simple script that grabs the hour and minute, does some calculations to determine if it's AM or PM, creates a string variable from those results, and then slips it inside of a specific DIV element. It does this every second.
Most of the code I've written seems to make sense based on what I've read. In the beginning I've tried using function displayCurrentTime() {} as well as what you see below (var displayCurrentTime = new function() {}) and neither seem to work. I cannot get my text to display in the page. Note: the ID of the div is notificationBar, just as it is here.
Is there anything in this code that makes no sense, or does this actually warrant posting the full HTML?
You don't need new in front of function that you newly define, you don't instantiate class.
You have few syntax errors, like var curMins : ... instead of var curMins = ....
Also, you cannot use getHours() and getMinutes() methods, outside of Date object:
var displayCurrentTime = function() {
// Get values...
var d = new Date();
var sysHour = d.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening = "AM"; // Initialize AM/PM notation
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = d.getMinutes(); // Get current minutes...
var curSecs = d.getSeconds(); //optionally get seconds too
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + ":" + curSecs + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(function(){ displayCurrentTime(); }, 1000);
<div id='notificationBar'>
Time Here
</div>
See about Date object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
About functions and anonymous function expression:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_expression_(function_expression)
Also:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Howto
There are a few syntax errors in your function, I'll get to them one by one:
You shouldn't use new when declaring a function. Just drop it =) var displayCurrentTime = function() {
You are trying to assign a value to a variable using json syntax : in var minutes: getMinutes. You also forgot to execute the function, so try var minutes = getMinutes();
In (2) I assume you already declared the methods getHours and getMinutes, but if not, you can call them directly from a new Date object:
var date = new Date();
var sysHours = date.getHours();
var minutes = date.getMinutes();
//...
That should do it!
Extra: you can skip adding the displayCurrentTime to another function inside the setInterval function: window.setInterval(displayCurrentTime, 1000);
var displayCurrentTime = function() {
var date = new Date(); // Get current date object
var sysHour = date.getHours(); // Get Hours
var curHour = 0; // Initialize current hour (12 hr format)
var morningEvening; // No need to initialize
if (sysHour < 13) { // If it's in the morning, set time as is.
curHour = sysHour;
morningEvening = "AM"
} else {
curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
morningEvening = "PM"
}
var curMins = date.getMinutes(); // Get Minutes
// Capture the ID of the notification bar div, and compose a string from the above values.
var notificationBar = document.getElementById("notificationBar");
var dateTimeString = curHour + ":" + curMins + " " + morningEvening;
// All that code above files into this fun stuff.
notificationBar.innerHTML = dateTimeString;
}
window.setInterval(displayCurrentTime, 1000);
<div id='notificationBar'></div>

Time things with Javascript

How can i time how much time passes between 2 events with javascript? like, to the millisecond?
When performing arithmetic operations on Date objects, they are implicitly converted to milliseconds (since 1970-01-01 00:00:00 UTC), so all you need to do is subtract a Date created when the operation started from a Date created when the operation ends.
var start = new Date();
doSomeHeavyWork();
var end = new Date();
var millisecondsElapsed = end - start;
Easiest way to do this.
console.time("timer name")
console.timeEnd("timer name")
This will output the time in milliseconds to the console.
It's surprisingly difficult to do.
var start = new Date();
// Do things here
var finish = new Date();
var difference = new Date();
difference.setTime(finish.getTime() - start.getTime());
alert( difference.getMilliseconds() );
Well, you can use firebug (firefox plugin) to benchmark your functions. Check this article : benchmark javascript funcions
What about making a reusable timer object?
Usage:
// event 1
document.getElementById('elId').onclick = function () {
timer.start('myTimer1');
};
// event 2
document.getElementById('otherElement').onclick = function () {
alert(timer.stop('myTimer1')); // alerts the time difference in ms
};
Implementation:
var timer = (function () {
var startTimes = {}; // multiple start times will be stored here
return {
start: function (id) {
id = id || 'default'; // set id = 'default' if no valid argument passed
startTimes[id] = +new Date; // store the current time using the timer id
},
stop: function (id) {
id = id || 'default';
var diff = (+new Date - startTimes[id]); // get the difference
delete startTimes[id]; // remove the stored start time
return diff || undefined; // return the difference in milliseconds
}
};
}());
var initialTime = (new Date).getTime(), i = 55000;
(function() {
while ( i-- ) {
setTimeout( function(){}, 20 );
}
})()
var finalTime = ( new Date ).getTime(), diff = (new Date);
diff.setTime( finalTime - initialTime );
alert( diff.getMilliseconds() + 'ms' )

Categories

Resources