JavaScript - How to handle the Daylight Savings in Europe - javascript

I am new to javascript and I am trying to console.log some values based on the business hours and off business hours in Europe
My Business hours are as below:
Monday-Thursday (08:00 - 16:00) & Friday 08:00-12:30
My Off-Business hours are as below:
Everything else apart from the business hours
Everything looks good but I am having a hard time handling the Day Light Savings.
According to the laws, the last Sunday in March and October are the breakpoints where the Daylight savings on and off.
Here's my code snippet:
function businessOrOffBusinessHours() {
var date = new Date();
var day = date.getDay();
var hours = date.getUTCHours();
var minutes = date.getMinutes();
console.log(date.getTimezoneOffset())
if (date.getTimezoneOffset() === 60) {
// Daylight savings
hours += 1;
console.log("daylight savings...")
}
hours += 2;
console.log(hours+":"+minutes)
if ((day >= 1 && day <= 4 && hours >= 8 && hours < 16) || (day === 5 && hours >= 8 && (hours <= 12 && minutes < 30))) {
console.log("Business Hours");
} else {
console.log("Off Business Hours");
}
}
businessOrOffBusinessHours()
The problem with above code is that even if I initialise the Date() object with a value like Date("2023-06-10T00:00:00Z") where the date falls exactly within the Daylight Savings window (i.e. last Sunday in March and October), I would still get the getTimezoneOffset() equals to 0
Can someone help me with this?
PS: I don't want to use any other third party javascript libraries or frameworks, I appreciate the solution to be fully in vanilla

Related

Does check day and hour need to check timezone?

My code to check day and hour like this :
function checkDay() {
var day = new Date();
if (day.getDay() >= 1 && day.getDay() <= 5 && day.getHours() >= 9 && day.getHours() < 17) {
return true;
} else {
return false;
}
}
I want every Monday to Friday 9 to 17, it's true. Apart from that, it is false
I had test it and it works. Is it necessary to check Timezone?
My position at Indonesia (GMT + 7)
If I implement timezone, it like this :
function checkDay() {
const offsetHours = new Date().getTimezoneOffset() / 60;
const day = new Date();
day.setHours(day.getHours() + offsetHours);
return day.getDay() >= 1 && day.getDay() <= 5 && day.getHours() >= 2 && day.getHours() < 10;
}
Is it necessary to check Timezone like that?
Your first piece of code is already correct because getHours and getDay already operate in the local time zone. As per the MDN Date documentation:
Note: It's important to keep in mind that while the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.
Likewise the ECMAScript specifications (e.g. ECMA 262, 2015 edition) describe the behaviour as going via the LocalTime abstract operation:
The abstract operation LocalTime with argument t converts t from UTC to local time

Check if weekday and time match

I'm currently looking for a solution to check if weekday is Tuesday to wednesday
so i want to display a message on my website from tuesday 10 pm to wednesday 05 am
How i can build this in a if else sniped?
If you're talking about the user's browser timezone:
// get time now
// local to user's timezone
var now = new Date();
// check if it is Tuesday and after 10 --OR-- check if it is Wednesday and before 5
if((now.getDay() == 2 && now.getHours() >= 22) || (now.getDay() == 3 && now.getHours() < 5))
{
// do yo thing chicken wing
}

Using JavaScript to change a message depending on the day of the week?

I am adding functionality to a website to change the message depending on if a food truck is open. I was successfully able to make the message change depending on the time, but I'm having trouble implementing getDay() to show the closed message all day on Saturday and Sunday.
Here is the working script that I have so far:
<script language="JavaScript">
var mess1="";
var outmess= "Kendo's Cuisine "
document.write("<center><font size=+1><i><b>")
day = new Date( )
hr = day.getHours( )
if (( hr >= 0 ) && (hr <= 11 ))
mess1= "is closed right now. He's open Mon - Fri 11am - 2pm. "
if (( hr >= 11 ) && (hr < 13))
mess1=" is open right now! Call in your order to have it ready by the time you get here!"
if (( hr >= 13) && (hr <= 14))
mess1= "usually runs out of food by now! Call before you come!"
if (( hr >= 14 ) && (hr <= 24 ))
mess1= "is closed right now. He's open Mon - Fri 11am - 2pm. "
document.write("<blink>")
document.write(outmess)
document.write("</blink>")
document.write(mess1)
document.write("</b></i></font></center>")
</script>
It seems you want to put up a "closed" message outside the hours of 11:00 to 14:00 Monday to Friday, so perhaps:
function isOpen(date) {
var day = date.getDay();
var hour = date.getHours();
if (day == 0 || day == 6 || hour < 11 || hour > 13) {
// shop is closed
return false;
}
// Otherwise, the shop is open
return true;
}
Note however that if the date object is created on the client, it will be local to that timezone, which may not match wherever the shop is. So you probably need to do this based on UTC time, which will be consistent everywhere.
Use getDay() method to get the weekday from date object. It returns a number from 0 - 6 to indicate days from sunday - saturday.
So you have to check like
var day = new Date();
if(day.getDay() == 0 || day.getDay() == 6) {
alert("shop is closed");
}

Check for working hours

I am trying to create a boolean function to check whether the current date/hour is a working hours. Now knowing that working hours are from 9AM to 5PM weekly except Fridays & Saturdays, I am facing issues with what I have come up with. I think my code works well for checking for days, but I just can't get it to work with hours as well. Here is my code:
var dayOfWeek = now.getDay();
//weekday 0==Sunday 1==Monday 2==Tuesday 3==Wednesday 4==Thurs 5==Friday 6==Sat
//Not Friday or Saturday
if ((dayOfWeek != 5) && (dayOfWeek != 6)){
if (now.getHours() >= 9 && now.getHours() < 17 ) {
//Within working hours now."
}
else
{
//After working hours."
}
}
}
Here is my HTML Code test on JSFiddle:
http://jsfiddle.net/jp9BW/
Changing my PC clock works. My test case is a working day starting 5PM. And that's when the problem happens. The else block is not hit.
I believe, this should be enough
function isWorkingHour(now) {
return now.getDay() <= 4 && now.getHours() >= 9 && now.getHours() < 17;
}
I would do it like this
function checkOpeningTimes() {
let date = new Date(); // current time
let hours = date.getHours();
let day = date.getDay();
let openingDays = [ 0, 1, 2, 3, 4 ];
return openingDays.includes( day ) && hours >= 9 && hours <= 17;
}

Need to display local times over DST transitions using Javascript Date Object

I am trying to output a series of times in hour (on the hour) intervals within Javascript (so inside a web browser such as Firefox). This series of times will overlap the short day (losing an hour in spring) and long day (gaining an hour in autumn). The output I'm looking for is in local time, i.e. with timezone and DST offsets applied. So for example, in the UK we have a missing hour from 01:00 to 01:59 on the short day such that the output would be:
00:00, 02:00, 03:00
And on the long day we have an extra hour from 01:00 to 02:00 such that the output would be:
00:00, 01:00, 01:00, 02:00, 03:00
I have already found these two brilliant answers that highlight some pitfalls and address part of my problem:
Daylight saving time and time zone best practices
Javascript Date objects and Daylight Savings Time
But the real difficulty is in making javascript aware of this missing and extra hour (so to speak) as identified in the second question mentioned above.
I think a potential solution to this would be to operate in UTC (aka GMT) and just do a conversion to local time but I'm struggling to see how I could do this.
Does anyone have any ideas about how to achive what I'm after?
If you have a fixed timezone, the following javascript code seems to work (tested on the last chrome version and firefox 6) :
// set the date to 11 / 04 / 2012 at 00:00 UTC
var date = new Date(1331424000000);
for(var i = 1; i <= 12; i++) {
$('.data-dston').append(' ' + date.getHours() + ':00, ');
date = new Date(date.getTime() + 3600000)
}
// set the date to 04 / 11 / 2012 at 00:00 UTC
var date = new Date(1351987200000);
for(var i = 1; i <= 12; i++) {
$('.data-dstoff').append(' ' + date.getHours() + ':00, ');
date = new Date(date.getTime() + 3600000)
}
Here's a JSFiddle : http://jsfiddle.net/Vsd2A/3/ to see the code in action !
Adapting what Krtek has come up with (for my timezone - UK) I now have the following:
// set the date to 27 / 03 / 2011 at 00:00 UTC
var date = new Date('27 Mar 2011 00:00');
for(var i = 1; i <= 12; i++)
{
$('.data-dston').append(' ' + date.getHours() + ':00, ');
date.setTime(date.getTime() + 3600000);
}
// set the date to 30 / 10 / 2011 at 00:00 UTC
var date = new Date('30 Oct 2011 00:00');
for(var i = 1; i <= 12; i++)
{
$('.data-dstoff').append(' ' + date.getHours() + ':00, ');
date.setTime(date.getTime() + 3600000)
}
Which has the benefit of not having to construct a new object on each iteration.

Categories

Resources