Reputation: 33
My client and server are in UTC(+1245) Chatham Islands Time Zone
In this time zone, the clock will go one hour ahead from 30th Sep 2018 02:45 to 30th Sep 2018 03:45.
I want that if someone sets the time in-between these hours, it should notify the user. I have used the following code for finding it but it is not showing.
https://jsfiddle.net/tt8dmm4y/5/
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(2018, 0, 1);
var jul = new Date(2018, 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.isDstObserved = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var checkdate = new Date(2018, 09, 30, 02, 55, 00);
if (checkdate.isDstObserved()) {
alert("Daylight saving time!");
}
Any help?
Upvotes: 1
Views: 64
Reputation: 241563
The Date
object in JavaScript will always work in the time zone that is local to the user. If you are comfortable with that, then simply compare the hours and minutes of the Date
object with what you put in:
function isInvalidLocalTime(year, month, day, hour, minute) {
var d = new Date(year, month-1, day, hour, minute);
return d.getHours() !== hour || d.getMinutes() !== minute;
}
isInvalidLocalTime(2018, 9, 30, 3, 0) // false, but only when local time is Chatham
When a time in a transitional gap is provided, the Date
object will shift it to some other time (which way it shifts is implementation dependent in older browsers). Note that minutes are required, because some time zone offset transitions are only 30 minutes, and not all transitions are related to DST.
If you need it to be specific to a particular time zone instead of a user-local time zone, then you will need to use a library that supports such things and take a similar approach as above while specifying the time zone. For example, we can use Luxon like this:
function isInvalidLocalTime(tz, year, month, day, hour, minute) {
var dt = luxon.DateTime.fromObject({zone: tz, year: year, month: month, day: day, hour: hour, minute: minute});
return dt.hour !== hour || dt.minute !== minute;
}
isInvalidLocalTime('Pacific/Chatham', 2018, 9, 30, 3, 0) // false
Also note that the Date
object and Luxon's DateTime
differ in whether months are zero-based or one-based. I accounted for that above (both functions are 1-based), but in your code in the question - you were testing October, not September.
Upvotes: 1