Based on date and time, show/hide element - javascript

I want to show and hide an element on a page based on multiple dates and times. For instance, I have an alert box that I want to show for the following dates 4/28, 4/29, and 4/30 between the hours of 9 am to 12 pm PST. And hide for the remaining hours. The posted code works for an open and closing time but I am unsure how I can add multiple dates. Or I'm just missing something.
Edit: I suck at jQuery/JavaScript.
HTML
<div class="open openstatus">Open</div>
<div class="closed openstatus">Closed</div>
JS
var now = new Date(),
currentDay = now.getDay(),
openTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
13,
02
),
closeTime = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
13,
03
),
open = now.getTime() > openTime.getTime() && now.getTime() < closeTime.getTime();
if (currentDay !== 6 && currentDay !== 0 && open) {
$('.openstatus').toggle();
}

I'd do something like this:
HTML
<div id="alertBox">My alert box</div>
JAVASCRIPT
function myFunc(){
var d = new Date(); //client Date
d.setMinutes(d.getMinutes() + d.getTimezoneOffset()); //To get current GMT time
d.setHours(d.getHours() - 8); // This is time in PST
var day = d.getDay(),
month = d.getMonth(),
hours = d.getHours(),
dateOfMonth = d.getDate();
var prohibbittedMonth = 4;
var prohibbittedDates =[28, 29, 30];
var showAlertBox = false;
if(day === 0 || day === 6){
showAlertBox = true; // If the day is Saturday or Sunday
}else if(month = prohibbittedMonth && prohibbittedDates.includes(dateOfMonth) && !(hours >= 0 && hours <9)){
showAlertBox = true;
}
// You may combine the above two condition in a single line. I have just separated them for better readability.
if(!showAlertBox){
document.getElementById('alertBox').style.display = "none"; //You may use your jquery here if you like
}else{
document.getElementById('alertBox').style.display = ""; //You may use your jquery here if you like
}
}
myFunc();

Cant't you add sth like this
currentDate=now.getDate();
if (currentDay !== 6 && currentDay !== 0 && open && (currentDate==28||currentDate==29||currentDate==30))
This checks if the currentDate is either 28 or 29 or 30.

Related

Script to open URL only on first Friday of the month and between 8am-10am

I'm working in Virtual Tour Software with Javascript and want to make an action, which will open an URL (with photo panorama) ONLY in particular part of time (in that case it's first Friday of month and only between 8am and 10am). Any ideas? Thanks Michal
For now I got somethink like this:
var startDate = new Date('Jun 5, 2020 8:00:00').getTime();
var endDate = new Date('Jun 5, 2020 10:00:00').getTime();
setInterval(function() {
var now = new Date().getTime();
var visible = now > startDate && now < endDate;
var hotspot = this.getPanoramaOverlayByName(this.getMediaByName('Panorama'), 'Hotspot');
if(hotspot && hotspot.get('enabled') != visible)
hotspot.set('enabled', visible);
}.bind(this), 1000);`
The problem is that I need to change "var start" and "var end" every time. I want to make it visible on every First Friday of month.
you can use getday() and getdate() function in js to find the day which is friday and date which is less or equal to 7 whatever the month and year is.
you can add following in your code like this:
var d = new Date();
var startDate = d.getDate(); // this will gives you only date
var isFriday = d.getDay(); // this will gives index of the day
var n = d.getHours(); // add this new line gethours
if((startDate <= 7 && isFriday == 5) && (n >= 8 && n <= 10)) // as indexing 5 for friday
{
setInterval(function() {
var hotspot = this.getPanoramaOverlayByName(this.getMediaByName('Panorama'), 'Hotspot');
if(hotspot && hotspot.get('enabled') != true)
hotspot.set('enabled', true);
}.bind(this), 1000);
}
try this.

How to show content timezone specific using javascript & html

My website currently displays the .pastTV div during the hours of
12:00pm-12:30pm EST. However, the code is not time-zone specific, capturing the local time of anyone visiting site.
Is there a way to make this specific to a UTC offset or timezone so that everyone is seeing (or not seeing) the same element?
My code works as expected when a visitor is in the Eastern timezone, otherwise it reads the local user time.
Update: Used this code instead for the same effect
var NYDate = new Date(new Date().toLocaleString("en-US", {timeZone: "America/New_York"}));
var NYHour = NYDate.getHours();
var NYMins = NYDate.getMinutes()
//12pm
if (NYHour >= 12 && NYHour <= 12 &&
NYMins > 0 && NYMins < 30) {
$('.pasttv, .life2').toggle();
}
var Now = new Date();
var CurrentDay = Now.getDay();
// opening time - 24 hours so 12:00pm is 12, 00
var OpeningTime = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 12, 00);
// closing time - 24 hours so 12:30pm is 12, 30
var ClosingTime = new Date(Now.getFullYear(), Now.getMonth(), Now.getDate(), 12, 30);
var Open = (Now.getTime() > OpeningTime.getTime() && Now.getTime() < ClosingTime.getTime())
// days 0.sun 1.mon 2.tues 3.wed 4.thur 5.fri 6.sat
// CurrentDay !== 0 && the # is the day to eclude, so if I want to be closed on Sat6, Sun0, Wed3
// CurrentDay !== 6 && CurrentDay !== 0 && CurrentDay !== 3 && Open
if (CurrentDay !== 0 && CurrentDay !== 6 && Open) {
$('.pasttv').toggle();
}
.hours {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="hours pasttv">
<font class="show-title">Past TVense</font><br> The first shows of the television medium
</div>
Have you tried using this? Date.prototype.getTimezoneOffset()
More info below:
"The time-zone offset is the difference, in minutes, from local time to UTC. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset

JavaScript application for showing the weekend dates?

I thought a lot - I tried but I could not solve it. I need a JavaScript application that shows the nearest weekend dates in the current date.
If it's a weekend now, give it the dates of this weekend, if not, then next weekend's dates.
I'm waiting for your help.
Respects.
You can use the built-in Date constructor.
var date = new Date();
var day = date.getDay();
var saturday;
var sunday;
if(day === 0 || day === 6){ //0 for Sunday, 6 for Saturday
saturday = date;
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (day === 0 ? -1 : 1));
if(day === 0){
var temp = saturday;
saturday = sunday; //Confusing, but they are actually the wrong dates, so we are switching the dates
sunday = temp;
temp = null; //Free up some memory!
}
}
else{
//This is the complicated part, we need to find when is the next Saturday
saturday = new Date(date.getFullYear(), date.getMonth(), (date.getDate() + 6) - day);
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (saturday.getDay() === 0 ? -1 : 1));
}
date = day = null; //Free up some memory!
document.body.innerText = [saturday, sunday];
To get the date, use saturday.getDate() or sunday.getDate().Remember that Date months are 0-based. See here for more info.
var chosenDay = new Date();
var box = [];
var counting = 0;
for (var i = 0; i < 7; i++) {
chosenDay.setDate(chosenDay.getDate() + counting);
var day = chosenDay.getDate();
var dayy = chosenDay.getDay();
var month = chosenDay.getMonth()+1;
var year = chosenDay.getFullYear();
box.push({day: day, dayy: dayy});
counting = 1;
};
Now to find Saturday and Sunday
box.map(function(obj) {
if (obj.dayy === 6) {
console.log('Saturday found');
alert(obj.day);
};
if (obj.dayy === 0) {
console.log('Sunday found');
alert(obj.day);
};
});
I interpret the "nearest" weekend as being the previous weekend for Monday and Tuesday, and the next weekend for Thursday and Friday. You didn't provide any information on what to do with Wednesday.
However, from other answers it seems you want either the current weekend for Saturday and Sunday and or the next weekend for weekdays.
The following is a little more concise than other answers:
/* Get nearest weekend to the provided date
** #param {Date} date - date to get weekends nearst to
** #returns {Array} array of Dates [Saturday, Sunday]
*/
function getNearestWeekend(date) {
// Copy date so don't mess with provided date
var d = new Date(+date);
// If weekday, move d to next Saturday else to current weekend Saturday
if (d.getDay() % 6) {
d.setDate(d.getDate() + 6 - d.getDay());
} else {
d.setDate(d.getDate() - (d.getDay()? 0 : 1));
}
// Return array with Dates for Saturday, Sunday
return [new Date(d), new Date(d.setDate(d.getDate() + 1))]
}
// Some tests
[new Date(2017,0,7), // Sat 7 Jan
new Date(2017,0,8), // Sun 8 Jan
new Date(2017,0,9), // Mon 9 Jan
new Date(2017,0,12) // Thu 12 Jan
].forEach(function(d) {
var opts = {weekday:'short', day:'numeric', month:'short'};
console.log('Date: ' + d.toLocaleString('en-GB',opts) + ' | Next weekend: ' +
getNearestWeekend(d).map(d =>d.toLocaleString('en-GB',opts)).join(' and ')
);
});

How to check if two dates not on the same calendar day

How to check if two dates not on the same day. I came up with this solution but maybe there is a better way to do this:
var actualDate = new Date();
var isNotToday = dateToCheck.getDay() !== actualDate.getDay() || dateToCheck < actualDate - 24 * 60 * 60 * 1000;
Another option is using .toDateString() function to parse both dates into strings. The function formats output to: "Wed Jul 28 1993." Then you can compare both date strings.
actualDate.toDateString() === dateToCheck.toDateString()
// returns true if actualDate is same day as dateToCheck
Here's a Plunker:
http://plnkr.co/edit/J5Dyn78TdDUzX82T0ypA
And more from MDN:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
How about checking for the same day, month & year:
var isSameDay = (dateToCheck.getDate() == actualDate.getDate()
&& dateToCheck.getMonth() == actualDate.getMonth()
&& dateToCheck.getFullYear() == actualDate.getFullYear())
It would be safest to check day, month and year:
var isNotToday = dateToCheck.getDate() != actualDate.getDate()
|| dateToCheck.getMonth() != actualDate.getMonth()
|| dateToCheck.getFullYear() != actualDate.getFullYear();
This will ensure you don't get oddities when it comes to DST and leap years which could interfere otherwise.
function getStartOfDay(aDate){
//returns the very beginning of the same day
return new Date(aDate.getTime() - aDate.getTime() % 86400000);
}
var aDate1 = getStartOfDay(new Date());
var aDate2 = getStartOfDay(new Date(1981, 7, 3));
var result = aDate1.getTime() === aDate2.getTime();
Don't create the date object with a time so they're both generated at midnight. Then just check the epoch time.
new Date('11/12/2012').getTime() === new Date('11/11/2012').getTime()
> false
new Date('11/12/2012').getTime() === new Date('11/12/2012').getTime()
> true
new Date('November 12, 2012').getTime() === new Date('11/12/2012').getTime()
> true
new Date('12 November, 2012').getTime() === new Date('11/12/2012').getTime()
> true
The dates just need to be parseable by the Date object (I'm on chrome 23.0.1271.17 (Official Build 159779) beta) and if you don't pass a time they'll generate at midnight.
If you're getting a time, just drop it on the floor and test against midnight.
function isEqual(startDate, endDate) {
return endDate.valueOf() == startDate.valueOf();
}
var now =new Date();
var startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var endDate = new Date(2017, 0, 13)
var result = isEqual(startDate , endDate);
console.log(result);
Use a startOf method for instances of Date:
dateA.startOf('day').getTime() === dateB.startOf('day').getTime()
Here's the method:
Date.prototype.startOf = function(unit) {
var clone = new Date(this.getTime()), day;
/* */if (unit === 'second') clone.setMilliseconds(0);
else if (unit === 'minute') clone.setSeconds(0,0);
else if (unit === 'hour' ) clone.setMinutes(0,0,0);
else {
clone.setHours(0,0,0,0);
if (unit === 'week') {
day = clone.getDay();
clone = day ? new Date(clone - 1000 * 60 * 60 * 24 * day) : clone;
}
else if (unit === 'month') clone.setDate(1);
else if (unit === 'year' ) clone.setMonth(0,1);
}
return clone;
};

How to determine if date is weekend in JavaScript

If I have a date coming into a function, how can I tell if it's a weekend day?
var dayOfWeek = yourDateObject.getDay();
var isWeekend = (dayOfWeek === 6) || (dayOfWeek === 0); // 6 = Saturday, 0 = Sunday
var isWeekend = yourDateObject.getDay()%6==0;
Short and sweet.
var isWeekend = ([0,6].indexOf(new Date().getDay()) != -1);
I tried the Correct answer and it worked for certain locales but not for all:
In momentjs Docs: weekday
The number returned depends on the locale initialWeekDay, so Monday = 0 | Sunday = 6
So I change the logic to check for the actual DayString('Sunday')
const weekday = momentObject.format('dddd'); // Monday ... Sunday
const isWeekend = weekday === 'Sunday' || weekday === 'Saturday';
This way you are Locale independent.
Update 2020
There are now multiple ways to achieve this.
1) Using the day method to get the days from 0-6:
const day = yourDateObject.day();
// or const day = yourDateObject.get('day');
const isWeekend = (day === 6 || day === 0); // 6 = Saturday, 0 = Sunday
2) Using the isoWeekday method to get the days from 1-7:
const day = yourDateObject.isoWeekday();
// or const day = yourDateObject.get('isoWeekday');
const isWeekend = (day === 6 || day === 7); // 6 = Saturday, 7 = Sunday
I've tested most of the answers here and there's always some issue with the Timezone, Locale, or when start of the week is either Sunday or Monday.
Below is one which I find is more secure, since it relies on the name of the weekday and on the en locale.
let startDate = start.clone(),
endDate = end.clone();
let days = 0;
do {
const weekday = startDate.locale('en').format('dddd'); // Monday ... Sunday
if (weekday !== 'Sunday' && weekday !== 'Saturday') days++;
} while (startDate.add(1, 'days').diff(endDate) <= 0);
return days;
In the current version, you should use
var day = yourDateObject.day();
var isWeekend = (day === 6) || (day === 0); // 6 = Saturday, 0 = Sunday
Use .getDay() method on the Date object to get the day.
Check if it is 6 (Saturday) or 0 (Sunday)
var givenDate = new Date('2020-07-11');
var day = givenDate.getDay();
var isWeekend = (day === 6) || (day === 0) ? 'It's weekend': 'It's working day';
console.log(isWeekend);
var d = new Date();
var n = d.getDay();
if( n == 6 )
console.log("Its weekend!!");
else
console.log("Its not weekend");
The following outputs a boolean whether a date object is during «opening» hours, excluding weekend days, and excluding nightly hours between 23H00 and 9H00, while taking into account the client time zone offset.
Of course this does not handle special cases like holidays, but not far to ;)
let t = new Date(Date.now()) // Example Date object
let zoneshift = t.getTimezoneOffset() / 60
let isopen = ([0,6].indexOf(t.getUTCDay()) === -1) && (23 + zoneshift < t.getUTCHours() === t.getUTCHours() < 9 + zoneshift)
// Are we open?
console.log(isopen)
<b>We are open all days between 9am and 11pm.<br>
Closing the weekend.</b><br><hr>
Are we open now?
Alternatively, to get the day of the week as a locale Human string, we can use:
let t = new Date(Date.now()) // Example Date object
console.log(
new Intl.DateTimeFormat('en-US', { weekday: 'long'}).format(t) ,
new Intl.DateTimeFormat('fr-FR', { weekday: 'long'}).format(t) ,
new Intl.DateTimeFormat('ru-RU', { weekday: 'long'}).format(t)
)
Beware new Intl.DateTimeFormat is slow inside loops, a simple associative array runs way faster:
console.log(
["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][new Date(Date.now()).getDay()]
)
Simply add 1 before modulo
var isWeekend = (yourDateObject.getDay() + 1) % 7 == 0;

Categories

Resources