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

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';
}
}

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";
}

Output x if it is weekend

I have created this to check if time is between 17:00 / 23:00.
This works fine! But now I want to check if its weekend.
Can you help me?
var objDate = new Date();
var hours = objDate.getHours();
if (hours >= 17 && hours <= 23) {
document.write('<!--test1 -->');
}
else {
document.write('<!--test2 -->');
}
Use the getDay() method of the Date object (0 corresponds to Sunday and 6 to Saturday):
<script language="javascript">
var objDate = new Date();
var hours = objDate.getHours(),
dayOfWeek = objDate.getDay();
if(hours >= 17 && hours <= 23 && (dayOfWeek == 6 || dayOfWeek == 0)){
document.write('<!--test1 -->');
} else {
document.write('<!--test2 -->');
}
</script>
var objDate = new Date();
var hours = objDate.getHours();
var n = objDate.getDay();
if(hours >= 17 && hours <= 23){
alert('<!--test1 -->');
}
else{
alert('<!--test2 -->');
}
if(n == 0 || n == 6)
{
alert('Weekend');
}
else
{
alert('Weekday');
}

Shopify estimated delivery

I am looking to show an estimated delivery date on the product page for each delivery option we have. I have read through the code in Shopify Variants by Steph Sharp which would work brilliantly except we would need it to be fixed to the current day up until 3pm and then switch to the next working day after 3pm. (Basically taking away the option for the customer to choose the dispatch day.)
I can’t quite get it to work by butchering this code into our template. This is what I have butchered together which seems to work okay but rather than have MON, TUE, WED, … I want to set them as the future dates. Any advice?
EDIT: Also I heard Palec is after using a timer code with this code too. So I will add that in.
<script language="JavaScript">
function day(a) {
var date = new Date();
var days = ["Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri","Mon","Tue","Wed","Thur","Fri"];
var today = date.getDay();
if (today == 1) today = 0; //Monday
if (today == 2) today = 1; //Tuesday
if (today == 3) today = 2; //Wednesday
if (today == 4) today = 4; //Thursday
if (today == 5) today = 5; //Friday
if (today == 6) today = -1; //Saturday Moved To Monday
if (today == 0) today = -1; //Sunday Moved To Monday
h = date.getHours();
if (h <= 9) h = "0" + h;
time = h;
if (time > 15) today++;
var expected = today + a;
var main = days[expected];
document.write('STANDARD DELIVERY ESTIMATE: ');
document.write(main);
}
</script>
<body>
<script language="JavaScript">
day(1)
</script>
I would try something like this:
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if(hours > 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
(The code in the addWeekdays function is from this answer on Stack Overflow.)
This code just displays the day name (like the code in your question), but you can format expectedDeliveryDate however you want.
EDIT: I updated my code to use expectedDeliveryDate.toDateString() as specified in the comments. Note that you no longer need the days array or expectedDeliveryDay variable. (You've still got them in your answer but they're not being used.)
This is my final code, based on Steph Sharp’s answer.
function day(a) {
var date = new Date();
var hours = date.getHours();
// If after 3pm, add 1 day
if (hours >= 15) a++;
var expectedDeliveryDate = addWeekdays(date, a);
document.write(expectedDeliveryDate.toDateString() + ' with Standard Delivery');
}
function addWeekdays(fromDate, days) {
var count = 0;
while (count < days) {
fromDate.setDate(fromDate.getDate() + 1);
if (fromDate.getDay() != 0 && fromDate.getDay() != 6) // Skip weekends
count++;
}
return fromDate;
}
Also added a timer:
function ShowTime() {
var now = new Date();
var hrs = 15 - now.getHours();
if (hrs < 0) hrs += 24;
var mins = 60 - now.getMinutes();
var secs = 60 - now.getSeconds();
timeLeft = "" + hrs + ' hours ' + mins + ' minutes ' + secs + ' seconds';
$("#countdown").html(timeLeft);
}
var countdown = setInterval(ShowTime, 1000);
function StopTime() {
clearInterval(countdown);
}

Get week days and specific time of day

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);

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