I am trying to hide a certain field on my website between the hours of 6 pm and 7 am and I was able to find a javascript that could solve that issue for me but the javascript came with getTimezoneOffset
which is set to 60000
and 3600000*offset
which I do not understand.
My time zone is (UTC + 01:00) West Central Africa.
In the javascript, I set the hours in which the field should be hidden to 16 = 4 pm
and 7 am
That is if (hour >= 16 || hour <= 7 {
but it isn’t working and I will like some help to fix or understand this problem.
See code sample below, thank you.
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
$(document).ready(function(){
//give the offset of your city
var offset = +1;
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
// return "The local time for city"+ city +" is "+ nd.toLocaleString() + "and time is "+nd.toLocaleTimeString() + " hour is "+nd.getHours();
var hour = nd.getHours();
console.log(hour);
if (hour >= 16 || hour <= 7 {
$("#daniel").hide();
} else {
$("#daniel").show();
}
});
</script>
<input id='daniel' placeholde='tunde' >
2
Answers
Your old code is commented and I have added the changes necessary.
EDIT: Make sure to check if hours are between 16 and 23 inclusive or 0 to 7 inclusive because the hours function return 0 to 23. Check the docs
if ((hour >= 16 && hour <= 23) || (hour >= 0 && hour <= 7))
Why don’t you just get the current hour directly and check if its between 16 and 7 ?
It’s as simple as
new Date().getHours()
Possible duplicate another StackOverflow question
The above code was working for me. I just corrected the typo error (added closing bracket for if condition)
if (hour >= 16 || hour <= 7 {
to
if (hour >= 16 || hour <= 7) {