I want to show up the time over my website based over the location of the user, let’s say if user one browsing the website is from USA than the time should be what is in USA currently and same for China etc. and all.
I was wondering if there exists a JavaScript plugin for it but I didn’t find any as dynamic as I want, my requirements include:
Something that can be fully stylized according to website theme (no iframes)
The pattern I want is to be in (HH:MM:SS)
It should be asynchronous like the second [SS] keep ticking and the time keep updating
Is this possible, a way around to achieve it?
Wouldn't this be enough?
html
<span id="time"></span>
js
$(function() {
var time = $("#time");
function getTime() {
var now = new Date(),
hours = now.getHours(),
minutes = now.getMinutes(),
seconds = now.getSeconds();
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
}
setInterval(function() {
time.text(getTime());
}, 1000);
});
Example
Just putting out the local system time of the user isn't enough?
If you want a server based solution, please take a look at the solution here. You have to find out the users timezone first and then manipulate the server time with an offset from the timezone using $dt->setTimezone(new DateTimeZone("Europe/Berlin"));.
Related
How would i go about a AUTO refresh code in Java or HTML that refreshes every 3 hrs and 45 min? Not like per user like even if its a user has been on the page only 10 min if its been 3 hours and 45 min since the last Refresh it will refresh anyway so like 3 hours and 45 min Server time not User time if that makes sense like 12:45 am 3:45 am 6:45 am 9:45 am 12:45 pm 3:45 Pm... Soo on soo on Hope this makes sense thanks for your help guys!
i have tried the following but it goes off user time
<meta http-equiv="refresh" content="13500" >
You can do this in plain JavaScript.
<script type="text/javascript">
setTimeout(function(){
//You can change this value based on the server location.
var offset = -5;
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
var serverTime = new Date(utc + (3600000*offset));
var hours = serverTime.getHours();
var minutes = serverTime.getMinutes();
if((hours % 3 == 0) && (minutes % 45 == 0)){
location.reload();
}
}, 30000);
</script>
You can include this script in your page and it will reload every three hours. The setTimeout is set to call every 30000ms or every 30 seconds.
Edit:
Added offset value for handling multiple server time zones.
You can refer to this link for exact values.
Thanks #ChrisForrence for the suggestion.
Your code will refresh the webpage based on the server time.
To fix the issue you need to use a timer and add function using javascript and based on it you can start the timer when you access the page and after every regular interval, you can refresh.
Use this URl for sample code snippet : http://www.javascriptkit.com/script/script2/autofresh.shtml
var limit="****" // time like "225:00" minutes
function beginrefresh(){
if (parselimit==1)
window.location.reload()
else{
parselimit-=1
curmin=Math.floor(parselimit/60)
cursec=parselimit%60
if (curmin!=0)
curtime=curmin+" minutes and "+cursec+" seconds left until page refresh!"
else
curtime=cursec+" seconds left until page refresh!"
document.title = doctitle + ' (' + curtime +')'
setTimeout("beginrefresh()",1000)
}
}
Hope this helps.
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 have a functie that keeps track of the local time live. I'm using the new Date(); object to get the local hours, minutes and seconds.
I also want the user to give a input where a function has to start on a specific time. The input of the user is a string (I don't want the user to work with the Date(); object as not all users can program). For example:
Input user:
var timeStart = "10:08:30";
Live time converted to string:
var sTime = todayHours + ':' + todayMinutes + ':' + todaySeconds;
When the two are equal:
if(sTime == timeStart )
{
//function when equals time
//This function has a timeout, so it will run infinite times
var timeOutId = setTimeout(function()
{
//call functie
}, 10000); //every 10 seconds as example
}
Alright this work just fine. I can compare strings only if they are the same or not. However to make it a little bit more complicated: I also want the user to give a end time, when to function has to stop:
Input user:
var timeEnd = "11:08:30";
Live time converted to string:
var sTime = todayHours + ':' + todayMinutes + ':' + todaySeconds;
When the two are equal:
if( sTime == timeEnd)
{
//function when equals time
//calls the timeout id and stops it
clearTimeout(timeOutId);
}
Now this just works fine! However now you know what i'm trying to do i'm wondering if i can do in some way:
if(sTime >= timeStart && sTime <= timeEnd)
{
//timeout will only be set when it's in between the given time
setTimeout(function()
{
//call functie
}, 10000); //every 10 seconds as example
}
Question
I there a way i can transform my string time(using 2-digits method) in a excisting date time so i can compare it on time?
My time only uses [hour, minutes and seconds], which causes problems as the Date(year, month and day) is not defined.
I've tryed to use Momentjs but it also refuses to work with only hour, minutes and seconds. Or i might not be farmilier on how to do this.
The method i want to use seems much easier as i don't have to define when to cancel the timeOut.
Any help is appreciated!
P.s What i actually just have to accomplish is converting the string time to a unix time stamp (Of course other methods are welcome too).
Dont know moment.js but you could still use basic parseInt to extract the time , turn it into and integer so you can compare it with another one :
function stringtime_to_seconds(aString){
var time,a = aString.split(":");
switch(a.length){
default: // 3 , you'll need to handle other cases
time = parseInt(a[0])*3600+parseInt(a[1])*60+parseInt(a[2]);
}
return time;
}
then you can compare dates.
I've tryed to use Momentjs but it also refuses to work with only hour, minutes and seconds. Or i might not be farmilier on how to do this.
...
What i actually just have to accomplish is converting the string time to a unix time stamp
You simply need to provide the format string, such as:
// parse the input
var timeStart = "10:08:30";
var m = moment(timeStart,"HH:mm:ss");
// then one of these
var s = m.unix(); // unix time in seconds
var ms = m.valueOf(); // unix time in milliseconds
Of course, to get unix time you have to have a specific date in mind. With the above method, it will use the local time zone's "today". This might be a concern if you have a range that spans over midnight, such as 10pm - 2am, so you might need to adjust.
Also, you said you were doing a range comparison like:
if(sTime >= timeStart && sTime <= timeEnd)
You probably should not do that with strings. But also, you should use a half-open interval [start,end). In other words:
if(sTime >= timeStart && sTime < timeEnd)
Usually when someone says 1:00 to 2:00, they mean that the range is over at 2:00.
I've been trying to figure this out for the past few days but only losing my hair over it.
I'm using the javascript below for a timer that counts up using a timestamp as the start date. I'm using a timestamp from the database, which is saved at the very moment that the timer is started, because that timestamp is saved relative to the user's timezone, which is selected in their profile.
My server php timezone is set to 'America/Los_Angeles'. My user profile timezone is also set to that. That is also the format in which the timezone is saved.
However when I run the timer, even though my php displays the correct saved time based on the saved timezone, ie. '05/29/2013 6:05:49', the timer has additional hours from the get-go. So it would look like "0 days 12 hours 0 mins 13 secs" instead of "0 days 0 hours 0 mins 13 secs".
This must be due to the javascript timezone??, since if I set my TZ to 'America/New_York' for instance, it would be "0 days 9 hours 0 mins 13 secs", correct?
How would I fix this?
JS
<script type="text/javascript">
function DaysHMSCounter(initDate, id){
this.counterDate = new Date(initDate);
this.container = document.getElementById(id);
this.update();
}
DaysHMSCounter.prototype.calculateUnit=function(secDiff, unitSeconds){
var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}
DaysHMSCounter.prototype.calculate=function(){
var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
this.days = this.calculateUnit(secDiff,86400);
this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}
DaysHMSCounter.prototype.update=function(){
this.calculate();
this.container.innerHTML =
" <strong>" + this.days + "</strong> " + (this.days == 1? "day" : "days") +
" <strong>" + this.hours + "</strong> " + (this.hours == 1? "hour" : "hours") +
" <strong>" + this.mins + "</strong> " + (this.mins == 1? "min" : "mins") +
" <strong>" + this.secs + "</strong> " + (this.secs == 1? "sec" : "secs");
var self = this;
setTimeout(function(){self.update();}, (1000));
}
window.onload=function(){ new DaysHMSCounter('05/29/2013 6:05:49', 'timer'); }
</script>
HTML
<div id="timer"></div>
First, you need to consider that you are interested in starting your timer from a specific moment in time. You cannot represent that with a local calendar date time like 05/29/2013 6:05:49 because of a few things:
The user will likely be in a different time zone
The user may use a different date format (MM/DD/YYYY vs DD/MM/YYYY)
The time may be ambiguous due to Daylight Saving Time transitions
So instead, you should pass a UTC value to your user. The browser will automatically take care of adjusting for the user's local time zone.
You can represent that value as an integer number of millseconds past Jan 1st 1970 UTC, or you can represent it in a standardized format, such as ISO8601, such as either 2013-05-29T13:05:49Z or 2013-05-29T06:05:49-07:00. PHP does have facilities to produce any of those representations. For example, you can use gmdate. See this answer for an example.
If you choose to go with the ISO8601 format, you should be aware that it was a late addition to JavaScript, and is not supported natively by all browsers. Most newer browsers do support it, but if you want the best compatibility, you will need to use a library such as moment.js (which offers many other great features as well).
If you go with an integer value, you won't need a library and can pass it directly to the Date constructor, but you may find it more difficult to debug.
Also, for reasons mentioned in this post, you might want to set your server time zone to UTC instead of America/Los_Angeles.
Your problem is that you are passing in the date in text format without the timezone. Thus the date is created in your local timezone.
If you instead have your server send the number of milliseconds past epoch (instead of string formatted date), then you can use new Date( millisPastEpoch ) and all should be good.
Alternatively, if you are guaranteed to know the user's timezone, then you can send the date formatted in the user's timezone instead of the server's.
I'm working on a busing website project and the buses run every hour. I'm having trouble creating a widget that finds the time between now and the next hour, so that it is clear when the next bus will run. My client requires that it is in javascript. Any suggestions?
Thanks in advance.
To know exactly the miliseconds from now to the next hour:
function msToNextHour() {
return 3600000 - new Date().getTime() % 3600000;
}
Please note that this will strictly tell you how many milliseconds until the NEXT hour (if you run this at 4:00:00.000 it will give you exactly one hour).
function getMinutesUntilNextHour() { return 60 - new Date().getMinutes(); }
Note that people who's system clocks are off will miss their bus. It might be better to use the server time instead of the time on the client's computer (AKA at least partly a non-client-side-javascript solution).
you have the Date object in Javascript, you could do something like:
var now = new Date();
var mins = now.getMinutes();
var secs = now.getSeconds();
var response = "it will be " + (60 - mins - 1) + " minutes and " + (60 - secs) + " seconds until the next bus";
of course you will have to work more on those calculations, but that's how you work with time in javascript
Either of the other two answers will work well, but are you aware of the docs available to you about all the other nice things date is JS can do for you?
Mozilla Date Docs
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Lots of answers, a really simple function to get the rounded minutes remaining to the next hour is:
function minsToHour() {
return 60 - Math.round(new Date() % 3.6e6 / 6e4);
}