I'm trying to write a JavaScript code that will display a certain message between two hours in a day. We're in eastern standard time but I have no problem working with universal time, because that makes writing the script much easier. So far, I have this and it works great, however, I'm completely stumped with regards to working with daylight savings time.
$(document).ready(function(){
var todaysDate = new Date();
var weekday = todaysDate.getDay();
var universalhour = todaysDate.getUTCHours();
if (weekday >= 0) {
if (weekday <= 4) {
if (universalhour >= 14) {
if (universalhour < 23) {
$('div#announcements span').append('<br />Open.');
}
}
}
}
if (weekday == 5) {
if (universalhour >= 14) {
if (universalhour < 20) {
$('div#announcements span').append('<br />Open.');
}
}
}
});
Basically, the message "Open" should only display between 10am EST and 8pm EST, Sunday-Thursday and 10am EST to 4pm EST Friday.
I have no problem working with UST, I just need help figuring out a workaround for Daylight Savings Time, as this i sbeyond my field of knowledge.
Case 1
If your computer is set to run on the Eastern Time Zone and you use this change:
var hour = todaysDate.getHours();
Then use that variable in all the tests.
That should take care of it.
Case 2
If you are writing JavaScript to run on a client machine at the end of some network/internet connection, you will need to pass something from the server to the client so the javascript can
tell what the time is in the Eastern Time Zone.
So you could include the following in your web page
<script>
// The global value is filled in by the server based on current time on your server which is
// running EST or can calculate it. That code might be PHP or Java or Ruby or ...
var ESTOffset = 5.0;
</script>
Then you have to use a calculation like this:
var hour = todaysDate.getUTCHours() + ESTOffset;
The hard part about that is is you display the message and expect it to change based on Eastern time. What if the user pops up the page and leaves it up until DST starts in EST? Do you need to handle that? What about if its almost 2 PM in EST and the page pops up? Do you have to pop up the message a few minutes later?
Case 3
You are in trouble if you need to figure out EST time, including DST, on a computer running an arbitrary time zone. There is nothing in javascript that lets you ask "What time is it in New York, USA?". You would need some library that knows the rules and that you will have to update (or make sure gets updated) if the rules change in EST. OR you could add some code yourself that knows when DST starts and ends in EST and does the math. Of course, then you have to update the code if the rules change.
This is easiest to do with a library. Using moment.js with moment-timezone:
$(document).ready(function(){
var now = moment().tz("America/New_York");
var weekday = now.day();
var hour = now.hour();
var isOpen = (weekday >= 0 && weekday <= 4 && hour >= 10 && hour < 20) ||
(weekday == 5 && hour >= 10 && hour < 16);
if (isOpen) {
$('div#announcements span').append('<br />Open.');
}
});
Be sure to include the data for the America/New_York zone from the time zone data builder. This is the IANA time zone identifier for US Eastern Time.
The primary advantage here is that you can express your hours in terms of local time, which will take into account any variations of daylight saving time automatically. In other words, these times are in the US "Eastern Time" zone, rather than having to be specifically in either "Eastern Standard Time" or "Eastern Daylight Time".
Related
I'm trying to get time of day for someone visiting my site. Seems easy enough, but the tricky part is that people may be traveling from other timezones and not changing their system clock. Using the below:
var d = new Date();
var currentTime = d.getHours();
console.log( currentTime );
if(currentTime < 12){
var tod = "morning";
}else if(currentTime >= 12 && currentTime <= 17){
var tod = "afternoon";
}else{
var tod = "evening";
}
document.write("hour of day is: "+currentTime);
console.log("Time of day is: "+tod );
I was able to detect local system time. For example, if my clock says 7:06 AM, then the variable currentTime will be 7. This works based on the system clock. So if I change my time zone to Eastern, currentTime will be 10 instead of 7. The problem is I'd like to detect the time of day where the user is actually sitting at that moment. So if I'm on the East coast and my system clock says 7AM, I still want to show the user a 10. I want to detect the hour of day it actually is where the user is by IP address. I have found a way to collect IP address, but not sure how to use it to get the local time.
If there is another way I am also open to that as well. Thanks.
Some might suggest getting it from the server, but I am using marketing cloud and there does not appear to be a way to do it. I've used the available AmpScript functions and they do not work as I would have expected.
Use any API that will respond with user's timezone. For example this one:
http://ip-api.com/json
And calculate user's time basing on it.
Updated: See below original post.
Start original post
Working on changing my client's chat button to an "offline mode" if a user visits the site outside the chat hours of operation.
Hours of operation are 9am-5pm Eastern Time (American, not Australian) Monday through Friday. When I say Eastern Time, it does need to take into account for Winter/Summer months for EST/EDT.
EST is UTC - 5 during winter months (1st Sunday in November until 2nd Sunday in March)
EDT is UTC - 4 during summer months (2nd Sunday in March until 1st Sunday in November)
To avoid problems (visitor might not have computer time set correctly) I opted to use getUTCDay() and getUTCHours() instead of getDay() and getHours().
To convert the UTC time into EST/EDT, I subtracted getTimezoneOffset() from getUTCHours() (dividing getTimezoneOffset() by 60 to get hours instead of minutes first). The reason I went with this method is because according to the Spec getTimezoneOffset() is not a constant and takes into account Daylight Saving Time.
All seems well (I think) until the if statements (which is where I believe I went wrong)
Fiddle link: http://jsfiddle.net/TLJsv/
Javascript
function chatOffline() {
var d = new Date();
var currentMonth = d.getUTCMonth();
var currentDay = d.getUTCDay();
var currentHours = d.getUTCHours();
var currentMinutes = d.getUTCMinutes();
var currentSeconds = d.getUTCSeconds();
var offSet = d.getTimezoneOffset() / 60;
var offMode = function offMode() {
jQuery('.initChat').css('background-position', '-68px 0px'); //switches sprite to offline position
jQuery('.initChat').css('cursor', 'context-menu'); //changes cursor so button appears to be not clickable
};
//set UTC time to either EST or EDT
currentHours -= offSet;
//check if day is between Mon-Fri
if (currentDay < 1) {
offMode(); // It's Sunday
} else if (currentDay > 5) {
offMode(); // It's Saturday
} else {
//check if time is earlier than 9am
if (currentHours < 9) {
offMode(); // It's before 9am ET
} else if
//check if time is later than 5pm
(currentHours > 17) {
offMode(); // It's after 5pm ET
} else if
//check if it is 5pm
(currentHours == 17) {
//if it's past 5pm, even by a second, go offline
if (currentSeconds > 0) {
offMode(); // It's after 5pm ET
}
}
}
}
chatOffline();
Fiddle link: http://jsfiddle.net/TLJsv/
During testing I changed the numbers in lines 23, 27, and 31 (currently the number 9 and number 17) to different values to confirm the chat link goes to offline mode. It doesn't work every time. I think the problem is with the if statement on line 23 (which checks if time is earlier than 9am). The next two seem to work fine.
Any help or improvements on this would be greatly appreciated!
End original post
Update
I realized I had my last 2 else ifs in wrong order, I've updated the fiddle http://jsfiddle.net/TLJsv/3/
If you don't want the user's clock to come into play, you'll have to do this on the server. There's no magic in getUTCHours that reaches out to a server for the time. It still uses the time in the Date object, which is obtained from the user's clock.
However, if you don't care about that, then the easiest way to do this in client-side JavaScript would be to use moment.js with the moment-timezone add-on.
var m = moment().tz("America/New_York"); // US Eastern Time Zone
if (m.day() < 1 || m.day() > 5 || m.hour() < 9 || m.hour() >= 17) {
offMode();
}
Note also that when it comes to ranges that include a time, humans usually mean this to be a half-open interval (ie. 9AM-5PM includes 9AM, but excludes 5PM). When ranges don't include a time, then humans usually mean it to be a fully inclusive interval (ie. Mon-Fri is 5 days, not 4).
I need script that will display "Open" & "Close" function on my site.
Script should display "OPEN" every day from Monday to Friday from 08:00am to 19:30pm
and for Saturday should display "OPEN" from 08:00am to 15:00pm (else display CLOSED)
Sunday is CLOSED all day long.
I try to manage this script but I was not able to achieve it:
var Digital=new Date()
var hours=Digital.getHours()
if (hours>=08:00&&hours<=19:30)
document.write('Open')
else if (hours>=19:31&&hours<=07:59)
document.write('Close')
but i need addition for the days, this is just for time.
The hours variable will be an integer number, you need to compare it to a number, like this:
if (hours >= 8 && hours <= 19)
document.write('Open')
else if (hours >= 19 && hours <= 7)
document.write('Close')
When rewrite those methods, you will need to get and compare the minutes from the Digital variable too.
You need to check the current date using if statements before checking the time. Your formatting was slightly off, as digital.getHours() returns a whole number rather than those formatted strings.
I also added a setInterval to update the status every minute, in case the page is left open for prolonged time.
Here is the fiddle: http://jsfiddle.net/u6bwJ/1/
EDIT: Fixed a few bugs (namely typos). I also see you need localization for this. I made some changes to the top of the code which adjust for timezone, so it's always displaying information based on local time. There is one caveat though, and that is that it is currently hardcoded to include daylight savings. This means it will be inaccurate once DST switches.
Line 10:
utc1Time=new Date(localTime.getTime() + (localTime.getTimezoneOffset() + 120) * 60000);
That + 120 is adding 2 hours after converting client time to UTC time, which makes it UTC+1 and then adds the DST offset. You will need to add some way to check if DST is in effect, something along the lines of
utc1Time.toString().match(/daylight/i)
but I will leave that to you, as this is probably enough of a framework for you to build upon.
Hope this helped :D
I have a javascript application which receives data from ASP.NET WebService in JSON format. My application has a lot of manipulations with dates which it also receives from WebService.
WebService stores all dates in EST timezone and sends them in such format:
{"Date":"\/Date(1319205600000+0300)\/"}
to my javascript application.
On the client side I should display all dates also in EST timezone irrespectively of browser's timezone. So if I receive from the server the representation of:
10/21/2011 10:00
I should display exactly the same time to the user.
So to convert dates I do something like this:
function convert_date(millisec) {
var date = new Date(millisec),
local_offset = date.getTimezoneOffset(),
server_offset = -5 * 60, //EST offset
diff = (local_offset + server_offset) * 60000;
return new Date(millisec + diff);
}
But the point is that server_offset not always should be -5. It can be -4 depending on DST value. I've tried to do server_offset = (date.isDST() ? -4 : -5) * 60 instead but I haven't found any solution for capturing isDST() which works fine for all the local client timezones. Most of them work fine for that local browser's timezone which has the same value of DST as EST timezone but would fail in the case of GMT+5:30 timezone for example.
So are there any way to determine whether DST would be applied for some specific date in EST timezone from javascript?
Or maybe I've missed something?
If you can modify the web service, I would have it also return a flag indicating whether or not it was daylight saving time in the server's timezone (EST).
Assuming you can't do this, you can determine whether it is daylight saving time according to this information for DST in the United States:
DST starts on the second Sunday of March and it ends on the first Sunday of November.
The caveat being that this could change in the future (I wasn't even aware it had changed in 2007).
I am not really sure how exactly you are getting the ticks value you pass to the function, which I think you have something weird going on there.
But if the question is how to write the isDST() function, then that should be pretty simple.
Date.prototype.isDST = function()
{
var dt = new Date(this.getYear(), 1, 1);
return dt.getTimezoneOffset() > this.getTimezoneOffset();
}
edit: This isn't polished/tested for negative offsets.
I have no acess to php. Is this possible w/ jquery?
Here is an example.
lets say the business opens at 11:00am and closes at 7:00 and the would like for a live chat image to say 'we're online!' but when they're closed they want the image to say 'we're offline'.
Does this help? If anyone has a solution to this please help. thanks.
You could get the client date using the Date object and datejs to simplify date manipulations like parsing, ...
Here's how to compensate for other timezones using Central Standard Time as the server's timezone:
http://jsfiddle.net/pxfunc/AcFhg/2/
javascript/jQuery:
// Translate your hours to UTC, example here is using Central Standard Time (-0500 UTC)
// Opening hour in UTC is 16, Closing hour is 0 the next day
var d = new Date(),
open = new Date(),
closed = new Date();
// Statically set UTC date for open
open.setUTCHours(16); // Open time at 11:00 am CST which is 16:00 UTC
open.setUTCMinutes(0);
open.setUTCSeconds(0);
open.setUTCMilliseconds(0);
// Statically Set UTC date for closing
closed.setUTCDate(d.getUTCDate()+1); // UTC time rotates back to 0 so we add a day
closed.setUTCHours(0); // Closing time at 7:00 pm CST which is 00:00 UTC (so we need to add a day)
closed.setUTCMinutes(0);
closed.setUTCSeconds(0);
closed.setUTCMilliseconds(0);
// Debugging
console.log("user's date:" + d);
console.log("store open time in user's timezone:" + open);
console.log("store close time in user's timezone:" + closed);
console.log(d > open); // user's time is greater than opening time
console.log(d < closed); // is user's time less than closing time (you don't have to go home...)
// Test for store open?
if (d > open && d < closed) {
setOpenStatus(true);
}
else {
setOpenStatus(false);
}
function setOpenStatus(isOpen) {
$('#open').toggle(isOpen);
$('#closed').toggle(!isOpen);
}
Note: it would be really difficult to fully compensate for the various daylight savings changes around the world but this will work for most cases
As multiple people have pointed out, anything you do on the client machine will be based on the client time rather than your actual business time.
Why don't you put an image on the page, don't worry about changing anything on the page, and just change the image on your server when your business opens or closes?
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
if ((h > 18) || (h < 11)) {
$(img).src('closed.jpg');
}
<script type="text/javascript">
<!--
var objDate = new Date();
var hours = objDate.getHours();
var imgsrc = (hours > 11 && hours < 19) ? 'open.jpg' : 'close.jpg';
document.write('<img src="'+imgsrc+'" />');
//-->
</script>
hopefully following can help you a bit
http://www.w3schools.com/JS/js_if_else.asp