Timezone specific hide/show element script - javascript

Hi first time posting here so bear with me.
I've got a live stream that I want to show on Sundays between 6am and 2pm (CEST - Central European Summer Time)
I've got the first part down but how do I make it timezone specific? Make sense?
$(document).ready(function() {
var d = new Date();
var n = d.getDay();
var hour = d.getHours();
if(n == 0 && hour >= 6 && hour < 14)
{
$(".stream").show();
} else {
$(".stream").hide();
}
} );
PS I understand this doesn't hide it completely outside of those times and that's fine. I'm just looking for a solution that works on the client side.

Related

Doing math towards future date

I am trying to figure out how to calculate future date compared to current date. For Example: (think of Deadline as a Date field)
- If Deadline (value form) is in the future but <= 12/31 of the current year, “This Year”
- If Deadline (value form) is in the future but > 12/31 of the current year, “Future”
So far, I am unable to figure this out within my code.
I need help with var theFuture AND to create a var for "is future but <= 21/31 of current year.
var theFuture = new Date("January 01 2020");
//theFuture.setDate(today.getDate());
//Compare the two numbers
if (dateToCheck < rightNow || dateToCheck == rightNow) {
theTiming = "Overdue";
g_form.setValue('u_timing', theTiming);
}
else if (dateToCheck >= approaching) {
theTiming = "Deadline Approaching";
g_form.setValue('u_timing', theTiming);
}
else if (dateToCheck > theFuture){
theTiming = "Future";
g_form.setValue('u_timing, theTiming');
}
}
So, results should be: When the user selects a date from Deadline, another field called Timing will generate Text. Current, I am able to calculate if the date selected is today or before today, Timing will say "Overdue". Next, if the date selected is greater than today BUT within 180 days, Timing will say "Deadline Approaching". But, to get the rest that I mentioned above, I am stuck.
We use moment.js for working with dates it makes things a lot easier.
This will tell you if the date selected is today or not:
var iscurrentDate = moment().isSame(dateToCheck, "day");
if(iscurrentDate)
{
}
You can also do a similar thing for year
var iscurrentDate = moment().isSame(dateToCheck, "year");
if(iscurrentDate)
{
}
More info on moment here: https://momentjs.com/docs/

Calculate new date after calendar event drop

I have a JavaScript/Math question.
I am stuck with one task for two days now and I guess I am complete idiot as I can't figure it out...Screenshot
I am creating a week calendar with shifts from 7am untill 8pm., but I can have shift which is for example 2 days long (or more).
The problem is that I can drag and drop the calendar event on the calendar and then I need to calculate new dateTo from dateFrom which I get from the div I placed it on.
The issues is that when I try to drag and drop the item to another time I need to place dateFrom to whenever I dragged it, but then I need to calculate hours so I get the same amount of time, but the problem is when the event is stretched over multiple days I need the event to finish next date after 7 am and not in the middle of the night. For example I had event from 3pm to 5pm of next day and then I moved it to 7pm of next day so I need the event to finish at 9 am of next day.
Does anyone has the same issue or solution for this?
Hope it makes sense, thank you very much.
Here is the code I am using right now, it almost works, but sometimes I get the wrong date/time (usually it removes 10 hours from date).
export function getCorrectDateAfterDrop(originalDateFrom, originalDateTo, dateFrom) {
const NIGHT_TIME = 11;
dateFrom = moment(dateFrom);
originalDateTo = moment(originalDateTo);
originalDateFrom = moment(originalDateFrom);
let hoursDiff = moment.duration(originalDateTo.diff(originalDateFrom)).asHours();
const sign = Math.sign(hoursDiff);
if (originalDateTo.isAfter(moment(originalDateFrom).hours(20))) {
hoursDiff = (hoursDiff > NIGHT_TIME) ? (hoursDiff - NIGHT_TIME) : hoursDiff;
}
let finalDateToBeChecked = moment(dateFrom).add((hoursDiff * sign), 'hours');
let isDateFromSameAsDateTo = moment(dateFrom).isSame(finalDateToBeChecked, 'day');
if (isDateFromSameAsDateTo && finalDateToBeChecked.hours() < 20) {
// I think the problem is here, but I can't figure it out :D
return finalDateToBeChecked.format();
} else {
const diffUntilShiftEnds = moment.duration(moment(dateFrom).hours(20).diff(dateFrom)).asHours();
hoursDiff -= diffUntilShiftEnds;
const finalDateFrom = moment(dateFrom).add(1, 'days').hours(7);
const finalDateTo = moment(dateFrom).add(1, 'days').hours(7).add(hoursDiff, 'hours');
return getCorrectDateAfterDrop(finalDateFrom, finalDateTo, finalDateFrom);
}
}
Maybe I do not fully understand your question, but I think something like the following should work:
function getCorrectDateAfterDrop(originalDateFrom, originalDateTo, dateFrom) {
return originalDateTo - originalDateFrom + dateFrom;
}
// verify it works:
var origFrom = Date.parse('01 Jan 2018 05:00:00');
var origTo = Date.parse('02 Jan 2018 07:00:00');
var newFrom = Date.parse('02 Jan 2018 01:00:00');
var newTo = getCorrectDateAfterDrop(origFrom, origTo, newFrom)
console.log((Date.parse('03 Jan 2018 03:00:00') === newTo)) // true
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>

Momentjs - Get most recent Friday

I'm trying to get the start of (12:00am, or, 00:00am) of the most recent Friday. This has been working:
moment().isoWeekday(5).startOf('day').toDate()
But it only works Friday->Sunday, on Monday morning it will then refer to the upcoming Friday, in which case this would work:
moment().add('-1', 'week').day(5).startOf('day').toDate()
but I need it be dynamic and done in one line if possible, to where I don't to perform any checks on the current day.
Is there a way to always get the most recent Friday? Regardless of what the current day is.
Edit I'm also trying to get this to return the current day (friday) if executed on a Friday.
If you don't want to use a library, it's pretty straight forward
var date = new Date();
while ( date.getDay() !== 5 ) date.setDate(date.getDate() -1);
console.log(date)
With moment
var date = moment();
var friday = date.day(date.day() >= 5 ? 5 :-2);
and if millisecond accuracy doesn't matter, you could call moment() twice to make it one line (but I would much raher use a variable)
var friday = moment().day(moment().day() >= 5 ? 5 :-2);
Check this:
var date = moment().utc().isoWeekday(5);
if(moment().day() < 5) {
date = date.add(-1, 'week');
}
console.log('Recent friday starts:', date.startOf('day').toDate());
console.log('Recent friday ends:', date.endOf('day').toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.js"></script>

setInterval and 12 hour clock in javascript

I want to write a script that changes the hour displayed inside a <span> every second, starting from 8AM, and which keeps repeating like a 12 hours clock (11AM, 12PM, ..., 11PM, 12AM, 1AM, ...).
The image will change at 8AM and 8PM. At 8PM, the image will change to a sleeping face, and at 8AM the image will change back to a smile face. However, that is not a problem.
The problems are:
When I set var hour = Number(document.getElementById("time").textContent); then setInterval repeats the time without any problem. However, when I set var hour = 8 instead, and keep same code, then setInterval repeats only once. Can you let me know why it is like that and how to fix it with var hour = 8?
When the hour is repeatedly increased, I cannot make it smart to change back to AM when it reaches to 12 after passing noon (12PM). For example, the code works fine from 8AM to 11PM but when it reaches to 12, the PM does not change to AM. Can you show me how to fix it?
Lastly when I change var period = "AM" instead of using DOM getElementByID like above and keep same code, then it runs to 1PM and then changes to 2AM and never changes to PM again. Can you explain to me why it happens?
If you do not know what I am talking about, you can run my code and to understand more.
Here is the HTML:
<h2>Life goes on!</h2>
<p>The current time is : <span id = "time">8</span> <span id = "period"> AM</span></p>
<img id = "emoticon" src = "smile.gif" alt = "awake">
And here is my JavaScript code:
setInterval(function () {
var hour = Number(document.getElementById("time").textContent);
hour++;
var period = document.getElementById("period").textContent;
if (hour >= 12) {
hour = hour - 12;
period = "PM";
}
if (hour == 0) {
hour = 12;
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
Let me explain the problems of your code, using the same three points you made:
Your problem about var hour = 8; is that, if you set the hour inside the setInterval callback, your hour will be set to 8 at any second. Therefore, your setInterval doesn't work only once, but it gets run infinite times setting the time always to 9. To avoid this, you can move the variable outside and make it global, setting it to 8 before starting the setInterval.
To change "PM" back to "AM" when it reaches 12PM, just add an if statement (or, better, a ternary operator, like I did in the snippet below) to check if the period is either "PM" or "AM", and behave consequently. Also, be careful with the check: if you check directly on .textContent be sure that the text inside the <span> doesn't have any trailing space: use .trim() to remove extra spaces at the beginning and at the end of the string.
This is the same problem of point 1: you should make the variable period global, and then start the setInterval.
The logic of the following script is simple:
Increase the hour by 1
If the new hour equals 12, then switch to "PM" or back to "PM"
If the new hour is greater than 12, then reset it to 1
Display hour and period
Change from smile.gif to sleep.gif when it's 8PM, and vice versa when it's 8AM.
I also made some little changes to make code easier and faster to read. Here is a working code snippet:
var hour = 8,
period = "AM";
setInterval(function() {
if (++hour >= 12) {
if (hour > 12) hour = 1;
else period = (period == "PM") ? "AM" : "PM";
}
document.getElementById("time").textContent = hour;
document.getElementById("period").textContent = period;
if (hour == 8 && period == "PM") {
document.getElementById("emoticon").src = "sleep.gif";
document.getElementById("emoticon").alt = "sleep";
} else if (hour == 8 && period == "AM") {
document.getElementById("emoticon").src = "smile.gif";
document.getElementById("emotion").alt = "awake";
}
}, 1000);
<h2>Life goes on!</h2>
<p>The current time is: <span id="time">8</span> <span id="period">AM</span></p>
<img id="emoticon" src="smile.gif" alt="awake">
Here it is, it works fine now, give it a try clicking on "Run code snippet".

Javascript between Two Times

I'm currently trying to create a JavaScript which will display on our website when our shop is open, and when it is closed.
I basically want to create an if statement between two times, these being 8:30 and 5:30.
I'm currently doing the following, although it won't work as I effectively have two lots of 'minutes' defined which cancel each other out.
<script type="text/javascript">
var Digital=new Date();
var day=Digital.getDay();
var hours=Digital.getHours();
var minutes=Digital.getMinutes();
// Monday - Open //
if (day==1 && hours>=8 && minutes>=30 && day==1 && hours<=17 && minutes<=30)
document.write('Open today until 5:30pm');
</script>
Can anyone suggest a way of achieving what I am trying to do?
How about this:
if(day == 1 && hours*60+minutes >= 510 && hours*60+minutes <= 1050) {
// do stuff
}
With 8 * 60 + 30 = 510 and 17 * 60 + 30 = 1050.
One thing to note here is
new Date()
gets the local time from the client's clock. If the client's clock is set at a different time zone you might not get the result you are hoping for.
I would suggest getting the client's timezone as well and converting that to your desired timezone adding/subtracting any offset, start with something like
var clientTime = new Date();
var clientTimeZone = clientTime.getTimezoneOffset();
//getTimezoneOffset returns the time-zone offset in minutes between the current locale and UTC.

Categories

Resources