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.
Related
before was getting time by timezone id using JavaScript this way.
var tz = jstz.determine(); // Determines the time zone of the browser client
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
alert(moment.tz('Europe/London').format(format));
OR
alert(moment.tz(tz.name()).format(format));
i was using two library one for getting timezone id from client browser and other one to get date & time based on timezone id. those two libraries are
<script type="text/javascript" src="Scripts/jstz.min.js"></script>
<script src="Scripts/moment.min.js" type="text/javascript"></script>
<script src="Scripts/moment-timezone-with-data-2010-2020.min.js" type="text/javascript">
but the problem is moment.js was giving time based on user pc date time setting. so if user pc date time is wrong then moment.js will return wrong date time. so i was looking for a way like how to get date & time by timezone id following ntp protocol.fortunately i got a solution from this url
their code as follows
// Get London time, and format it:
getTime('Europe/London', function(time){
var formatted = time.getHours() + ':'
+ time.getMinutes() + ':'
+ time.getSeconds();
alert( 'The time in London is ' + formatted );
});
$.getTime = function(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz='
+ zone + '&callback=?';
$.getJSON(url, function(o){
success && success(new Date(o.datetime), o);
});
};
how far i understand the above code that it will call time.json and pass timezone id and response will back a new date and time based on timezone id.
i have one question that
1) please tell me someone that above js routine will return right date and time based on timezone id?
2) what about latency is there. suppose i made call to time.json and got the response back after 10 sec may be due to slow internet or any other reason. in this situation how could i get correct date & time.
so guide me what i need to do to always get correct time with date if response back after few sec or minute. also discuss what other best way out there to get NTP date & time using javascript. looking for guidance.
he main issue is latency...if i get response back after few sec or minute then how could i re-calculate time to make it accurate for latency or slow response problem.....please guide me someone. thanks
I would like to make a page that greets the user with the classic "good morning/evening", depending on the time of the day. However, I understand that I can't just get the server time because if, say, a user in Japan viewed the page, it might receive a "good afternoon" at 5AM, which is obviously not correct :)
Can I get the time in the user's machine using PHP/JS, and if so, what function should I look at? Also, if JS is needed, how can I detect whether the user has a script blocker in place?
Sorry for the noobish questions, I am just starting to learn about web programming. Any help will be greatly appreciated. :)
Cheers!
- jfabian
PHP runs server side so it will only return the server time I believe.
Something like this in Javascript might work:
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10)
minutes = "0" + minutes
document.write("<b>" + hours + ":" + minutes + " " + "</b>")
You can get the user's timezone in javascript by using:
new Date().getTimezoneOffset() * -1
My suggestion would be to have your PHP page return UTC time e.g. with gmdate()
see get UTC time in PHP with UTC time you don't have to worry so much about things like daylight savings time, etc.
Then in your javascript you would determine the timezone offset of the user. You could use
new Date().getTimezoneOffset()
or for more advanced timezone stuff you may use a javascript library, see How to get user timezone using jquery? for some ideas.
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".
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 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