Get week days and specific time of day - javascript

I'm using javaScript to display an element on week days and in busines hours (Monday to Friday between 08:00 and 16:50).
I'm using this code:
var date = new Date();
var thisMin = date.getMinutes();
var thisHour = date.getHours();
var thisWeekday = date.getDay();
// True if Mon - Fri between 08:00 - 16:50
if (thisWeekday > 0 && thisWeekday < 6 && thisHour > 7 && (thisHour < 17 && thisMin <= 50)) {
alert("True");
} else {
alert("False");
}
- but is this the best way to code it? It seems like a lot of conditions and it's working all the time... Can it be done in a better way with javaScript?
Fiddle here.
Thanks.

Note that you have a condition with two distinct parts "must be within week interval" and "must be within time interval". The code can reflect this more clearly by being explicit.
For the time comparison I would reshape the current time so that you can use Date's <= and >= operators instead of reimplementing time comparisons yourself:
var startTime = new Date(0, 0, 0, 8, 0);
var endTime = new Date(0, 0, 0, 16, 50);
var startWeekday = 1;
var endWeekday = 5;
function shouldDisplay() {
var d = new Date();
function withinWeekInterval() {
return (d.getDay() >= startWeekday &&
d.getDay() <= endWeekday);
}
function withinTimeInterval() {
var now = new Date(0, 0, 0, d.getHours(), d.getMinutes());
return (now >= startTime &&
now <= endTime);
}
return (withinWeekInterval() && withinTimeInterval());
}
Manual test:
alert(shouldDisplay());

Try below Code :
var date = new Date();
var thisMin = date.getMinutes();
var thisHour = date.getHours();
var thisWeekday = date.getDay();
var isSuccess = false;
// True if Mon - Fri between 08:00 - 16:50
if (thisWeekday > 0 && thisWeekday < 6 && thisHour > 7 && (thisHour < 17)) {
if (thisHour == 16 && thisMin > 50) {
isSuccess = false;
} else {
isSuccess = true;
}
} else {
isSuccess = false;
}
alert(isSuccess);

Related

Javascript time condition between 11:40 AM and 12:20PM (11:40 < 12:20)

I tried the code below but it didn't work.
var hour = new Date().getHours();
var min = new Date().getMinutes();
if (hour >= 11 && hour <= 12 && min < 40 && min > 20) {
document.body.style.background = "green";
} else {
document.body.style.background = "red";
}
you had three problems here:
the extra } at the end
hours is not defined. I changed it to hour, which is defined
'=>': this is not necessary for the hours. since you are only checking two hours (11 and 12), it's much simpler to check each hour and it's minuets separately.
var hour = new Date().getHours();
var min = new Date().getMinutes();
if((hour == 11 && min >40) || hour == 12 && min < 20) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
This is just for this example.
var hour = new Date().getHours();
var min = new Date().getMinutes();
if (hour >= 11 && hour <= 12 && (hour === 11 ? min > 40 : min < 20)) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
You can use the javascript Date object and compare with the Date object between start time, end time and current time.
const date1 = new Date();
date1.setHours(11);
date1.setMinutes(40);
const date2 = new Date();
date2.setHours(12);
date2.setMinutes(20);
const today = new Date();
if (today >= date1 && today <= date2) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}
Your logic had some problems so I fixed them. This will change background to red if between the hours of 11:40 AM and 12:20 PM (inclusive):
var hour = (new Date()).getHours();
var min = (new Date()).getMinutes();
if (hour == 11 && min >= 40 || hour == 12 && min <= 20) {
document.body.style.background = "red";
} else {
document.body.style.background = "green";
}

How to exclude holidays dates in Angular/Javascript

I have not been able to find solution to this. Please, I wrote this code for calculating differences between business hours for a leave duration, I also took note of the lunch time and weekends. However, i want to extend it to accommodate holidays. For example, if the dates in the array ['2020-07-15', '2020-07-16', 2020-07-17'] are holidays. Please, how can i exclude these holiday days based on the dates passed in the array. Thanks
onChangeDate(){
var minutesWorked = 0;
var startDate = new Date(this.leaveList.date_from);
var endDate = new Date(this.leaveList.date_to);
var holidays = [ new Date (2020, 6, 27), new Date(2020, 6, 28 )]
if(endDate < startDate){
return 0;
}
var current = startDate
// Define work range
var workHoursStart = 8.30;
var workHoursEnd = 18;
var excludeWeekends = true;
var excludeLunch = true;
// Loop while currentDate is less than end Date (by minutes)
while(current <= endDate){
if(current.getHours() >= workHoursStart && current.getHours() < workHoursEnd && (excludeWeekends ? current.getDay() !== 0 && current.getDay() !== 6 : true)
&&(excludeLunch ? current.getHours() !== 12 && current.getHours() !==13.30: true)){
minutesWorked++;
}
current.setTime(current.getTime() + 1000 * 60);
}
this.leaveList.hours = Math.floor(minutesWorked / 60);
}
You should try another approach that will not only save no of iterations but also gives an effective solution.
Find no of hours per day ( conditioning the lunch hours)
Find no of days ( conditioning the weekend days)
function onChangeDate(){
var minutesWorked = 0;
var startDate = new Date(this.leaveList.date_from);
var endDate = new Date(this.leaveList.date_to);
var holidays = [ new Date (2020, 6, 27), new Date(2020, 6, 28 )];
holidays = holidays.map(function(holidayDate){
return holidayDate.toDateString();
})
if(endDate < startDate){
return 0;
}
var current = startDate
// Define work range
var workHoursStart = 8.5;
var workHoursEnd = 18;
var excludeWeekends = true;
var excludeLunch = true;
var lunchTime = 1.5; // define just the no of hours of lunch
var hoursPerDay = workHoursEnd - workHoursStart;
if(excludeLunch){
hoursPerDay = hoursPerDay - lunchTime;
}
var noOfDays = 0;
while(current <= endDate){
var currentDateValue = current.toDateString();
var currentDay = current.getDay();
if((!excludeWeekends || (excludeWeekends && currentDay < 6 && currentDay > 0))
&& holidays.indexOf(currentDateValue) == -1){
noOfDays++;
}
current.setDate(current.getDate() + 1);
}
var hours = hoursPerDay*noOfDays;
this.leaveList.hours = hours;
}

Compare Date range with moment.js

I am trying to get the following output:
Here is my code:
const start = "12/7/2018";
const end = "10/6/2019";
var startLease = moment(start, "MM/DD/YYYY");
var endLease = moment(end, "MM/DD/YYYY");
var array = [];
var i = 0;
var nextEnd;
while (1 == 1) {
var nextStart = nextEnd ? (nextEnd.date() > 28 ? nextEnd : nextEnd) : nextEnd || startLease.clone().add(i, 'M');
nextEnd = startLease.clone().add(i + 1, 'M') > endLease ? endLease : startLease.clone().add(i + 1, 'M');
if (nextEnd.date() > 28) {
nextEnd.subtract(1, 'days')
} else {}
array.push(nextEnd.diff(nextStart, 'days'));
if (nextEnd >= endLease) {
break;
} else {}
i += 1
}
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
Issue:
Instead of going from 7th-6th, it goes from 7th-7th of every month. I tried .subtract(1, 'days') but that doesn't output the correct values. However, this works for end of the month.
Any help is appreciated. Thank you.
I added some logging to your loop and cut it off after one iteration.
Only the first month is wrong for your example, so the issue is your expectation that if you add 1 month to December 7, 2018, you'll get January 6, 2019 (you'll actually get January 7, 2019).
I'm not sure what the condition that leads to subtracting a day is supposed to do. nextEnd.date() will resolve to the day of the month, which is always less than 28 for your example.
const start = "12/7/2018";
const end = "10/6/2019";
var startLease = moment(start, "MM/DD/YYYY");
var endLease = moment(end, "MM/DD/YYYY");
var array = [];
var i = 0;
var nextEnd;
while (1 == 1) {
var nextStart = nextEnd ? (nextEnd.date() > 28 ? nextEnd : nextEnd) : nextEnd || startLease.clone().add(i, 'M');
console.log(nextStart);
nextEnd = startLease.clone().add(i + 1, 'M') > endLease ? endLease : startLease.clone().add(i + 1, 'M');
console.log(nextEnd);
if (nextEnd.date() > 28) {
nextEnd.subtract(1, 'days')
} else {}
array.push(nextEnd.diff(nextStart, 'days'));
if (nextEnd >= endLease) {
break;
} else {}
i += 1;
break;
}
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
This worked for me:
while(1==1){
var nextStart = nextEnd ? nextEnd : startLease.clone().add(i, 'M');
var tempstart = startLease.clone();
tempstart.date(1);
if (startLease.date() < endLease.date() && array.length == 0) {
i = -1;
}
tempstart.add(i + 1, 'M');
var days = [31, 28, 31, 30, 31, 30 ,31, 31, 30, 31, 30, 31];
var year = tempstart.year();
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
days[1] = 29;
if (endLease.date() > days[tempstart.month()]) {
tempstart.date(days[tempstart.month()]);
} else {
tempstart.date(endLease.date());
}
nextEnd = tempstart > endLease ? endLease : tempstart;
var diff_sum = nextEnd.diff(nextStart, 'days');
array.push (diff_sum);
if (nextEnd >= endLease) {
break;
}
i += 1
}

Javascript check if the time is between 8:30am and 6:30pm

Ok so what the title says. I am doing this on a server, so I get the server's time using some PHP code. The problem is that it is a time frame without exact round hour values. Should I use nested if else statements?
var serverTimestampMillis = <?php print time() * 1000 ?>;
var checkInterval = 1000;
var checkTime = function () {
serverTimestampMillis += checkInterval;
var now = new Date(serverTimestampMillis);
var timeDiv = document.getElementById('timeDiv');
var messageDiv = document.getElementById('messageDiv');
timeDiv.innerHTML = now.toString();
var dayOfWeek = now.getDay(); // 0 = Sunday, 1 = Monday, ... 6 = Saturday
var hour = now.getHours(); // 0 = 12am, 1 = 1am, ... 18 = 6pm
var minutes = now.getMinutes();
// check if it's Monday to Thursday between 8:30am and 6:30pm
// this is where I don't know how to check 8:30
if (dayOfWeek > 0 && dayOfWeek < 5 && hour > 8 && hour < 18) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
else {
messageDiv.innerHTML = 'Sorry, we\'re closed!';
messageDiv.className='closed';
}
};
// check the time every 1000 milliseconds
setInterval(checkTime, checkInterval);
checkTime();
thank you in advance, and sorry for being a noob
Compare between two dates using a helper function:
function createDateTime(time) {
var splitted = time.split(':');
if (splitted.length != 2) return undefined;
var date = new Date();
date.setHours(parseInt(splitted[0], 10));
date.setMinutes(parseInt(splitted[1], 10));
date.setSeconds(0);
return date;
}
var startDate = createDateTime("8:30");
var endDate = createDateTime("17:30");
var now = new Date();
var isBetween = startDate <= now && now <= endDate;
console.log(isBetween);
JSFIDDLE.
You can just nest your statements, like you said (to make it easier to read), and then check the specific edge cases (8:30-9 and 18:00-18:30).
if (dayOfWeek > 0 && dayOfWeek < 5) {
if ((hour > 8 && hour < 18) ||
(hour == 8 && minutes >= 30) ||
(hour == 18 && minutes <= 30)) {
messageDiv.innerHTML = 'Yes, we are open!';
messageDiv.className='open';
}
}

Using boolean logic on time (javascript)

Javascript has built-in function for time where
var date = new Date();
d.getHours() //gets the hour in integer 0-23
d.getMinutes() //gets the minute in integer 0-59
I would like function (e.g. A()) to run between 0:35 and 4:35
Is this possible to do using just simple logic operation (&&, ||)?
I don't think it is possible, but I wanted to know the elegant way to implement it.
You could use the timestamp to compare.
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var start = new Date(year, month, day, 0, 35);
var end = new Date(year, month, day, 4, 35);
if (date.getTime() >= start.getTime() && date.getTime() <= end.getTime()) {
//...
}
var date = Date.now(); // ES5 - or new Date().getTime()
var sec = (date / 1000); // seconds since epoch
sec = sec % 86400; // seconds since midnight
var mins = sec / 60; // minutes since midnight
if (mins >= 35 && mins < 4*60+35) {
A();
}
Technically it's possible, but you are absolutely right in that this is not an elegant solution:
var h = d.getHours();
var m = d.getMinutes();
if ((h == 0 && m >= 35) || (h > 0 && h < 4) || (h == 4 && m <=35)) {
A();
}
This should work:
function foo(){
var now = new Date();
if( (now.getHours() < 1 && now.getMinutes() < 35)
|| (now.getHours() > 3 && now.getMinutes() > 35) ){
return false; //if it isn't in your time, return false
}
//put your code here. this will run between the hours of 12:35AM and 4:35AM local time
}
I hope this is what you are looking for. If not, let me know.

Categories