Display current updating time with user timezone - javascript

In my view, I have where the time is displayed for the user.
<h2 id="current_time">
<%= Time.now.in_time_zone(#user.time_zone).strftime("%-I:%M:%S %p") %>
</h2>
The #user.time_zone returns Pacific Time (US & Canada) and the time displays correctly. Now, I want to try and update this time using javascript so that it displays the current time if the browser is left open on this page.
Below is what I have updating the current time and this seems to work, but I cannot figure out how to get it to display in the user's time zone. It just reverts back to my system time.
How can I get this to update the current_time taking into account the user's time zone?
I tried passing the #user.time_zone to javascript, but it wants the region in Area/Location.
<script>
var current_time = setInterval(function(){system_time()},1000);
function system_time()
{
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("current_time").innerHTML = t;
}
</script>

Related

Get the real time of a user

I'm facing a problem to get the real 'trusted' user time, preventing them to cheat if they change their computer's time.
Weather I use a plain date object, or moment timezone or even google timezone api I just can't get the 'real' time of a user if I try manipulating the current time.
If we are at 20:00 (no matther the location) and the user tempers with the time to set it as 11:00 then I always end up with that time and not the real one, either by
const time = new Date();
const timestamp = (time.getTime() / 1000 + time.getTimezoneOffset() * 60);
const url = 'https://maps.googleapis.com/maps/api/timezone/json?location=-31.369926900000003,-64.2218601&timestamp=1568396292&key=MY_API_KEY';
this.httpDuplicate.get(url ).subscribe((res: any) => {
if (res) {
const dst = res.dstOffset;
const raw = res.rawOffset;
const fixed = (timestamp + raw + dst) * 1000;
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const currentTime = momenttz().tz(timezone).format();
console.warn('initial time ', new Date(time),
' - google time ', new Date(fixed),
' - moment timezone ', currentTime);
// all these values are wrong and point to 11:00 rather than 20:00
}
});
Is there a way to achieve this ? What I want in the end is to get the right time for a certain position... clearly not trusting the user's system time, but do trust its location (though there are ways to alter this as well)
The reason it fails is because you reference the Date object you made based on the user's client time ('time' variable).
If you don't trust the system time, you'd have to get the time from somewhere else, like an external server that you do trust, or the backend of your application if you have one (server time).
For example: http://worldtimeapi.org/
Of course, you'd also need the user's location in that case. I can imagine you don't trust that either since you also don't trust the time, so in that scenario there's no way to do it.

Browser seems to cache DateTime

I realized that a change in system time is not immediately reflected in javascript, event if I use a new Date object. It is only updated every minute.
var fakeElapsed = 0;
$(document).ready(function(){
var oldTime = 0;
function fakeTimeLoop(time){
fakeElapsed+=(time-oldTime);
oldTime = time;
$("div").html(fakeElapsed);
}
var clock = new Date();
var start = clock.getTime();
oldTime = clock.getTime();
setInterval(function(){
var clock2 = new Date();
var end = clock2.getTime();
var elapsed = end-start;
if(elapsed%5===0){
fakeTimeLoop(end);
}},
1
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div></div>
</body>
Time code, if you would turn time forward (or backwards), it takes a minute to change the time elapsed.
Is there anyway to update to the system time every second?
Edit: for those who are confused, a change in system is not reflected immediately on Chrome and Opera, but on IE and Mozzila, it is immediately reflected, I assume its order to avoid expensive system calls every time it needs to build a new Date object.
What I am looking for: is that anyway to get the current system time in chrome/opera or detect a change in system time immediately?
It's not exactly clear to me what you're trying to accomplish, but your setInterval is programmed to execute every millisecond (the second parameter is in milliseconds), but browsers treat any value less than 10 as equal to 10. Even with that restriction, the timing isn't guaranteed to be exact, so the function may well execute every 11, 12, 13, etc. milliseconds.
When you change your computer date/time and refresh the web page, new Date() will not return correct date/time. After 20-25 seconds it will return correct time. Probably it is a browsers' bug (I tested on Windows 10, Edge an Chrome).

How to display Current time of Dallas and australia

I'm trying to display current time of Dallas and Australia and I have come up with the Code,but it's not working . I'm completely new to Java script and Java here is my code , please help me out in achieving this
<script>
var now = new Date();
var now_utc = now.getUTCHours()-6+":"+ now.getUTCMinutes()+":"+ now.getUTCSeconds()
document.getElementById("inner1").innerHTML+=now_utc;
var aus= new Date();
var aus_time= aus.getUTCHours()+11
document.getElementById("inner2").innerHTML+=aus_time;
</script>
I want to display Current time of Dallas,London,Australia.
Thanks you all.
As once was pointed out by an Apple Engineer: never ever do calendar calculations by yourself. There are tons of small and large pitfalls that most people are unaware of and thus are not taking into account.
If you need an accurate depiction of the (current) time in another Timezone there is no other way then use a library that has all the information regarding Timezones and its peculiarities.
If you do not care about being exact every day of the year then this might be overkill but you have to decide for yourself.
For Javascript there exists the https://github.com/mde/timezone-js library, which itself uses the Olsen Database (https://en.wikipedia.org/wiki/Tz_database).
You have to download the Timezone-Infos and provide them along your source code. Then you can do all that TZ-related calculations/
// 'now' in the Timezone of Chicago (Central Time, should be equal to that of Dallas)
var dt_chicago = new timezoneJS.Date('America/Chicago');
// 'now' in London
var dt_london = new timezoneJS.Date('Europe/London');
// 'now' in Brisbane - you should look up which timezones
// there are in Australia and which you want to display
var dt_brisbane = new timezoneJS.Date('Australia/Brisbane');
I just found out that there is another library http://momentjs.com/timezone/ but I have not used it yet so I may not recommend or advise against using it.
The below piece of code will calculate the current time of any specific time zone. Just pass the time zone of any specific country it will show the current time.
function calcTime(city, offset) {
var d = new Date();
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
var nd = new Date(utc + (3600000*offset));
return "The local time for city"+ city +" is "+ nd.toLocaleString();
}
console.log(calcTime('Dhaka', '+6.0')));
console.log(calcTime('Australia', '+11.0')));
You use now variable break your script.On live var aus_time you forget semicolon at this line.
As #Traktor53 said in comment AU have multiple timezone.
Your code is OS dependent you will check after change your system time.you will get wrong time. Its better way to use google time API.
function gettz(){
var dnow = new Date();
var dnow_utc = dnow.getUTCHours()-6+":"+ dnow.getUTCMinutes()+":"+ dnow.getUTCSeconds()
document.getElementById("inner1").innerHTML+=dnow_utc;
var aus= new Date();
var aus_time= aus.getUTCHours()+11;
document.getElementById("inner2").innerHTML+=(aus_time);
return;
}
</script>

javascript - time counter since start date and time

I have a new business, where I just hired someone to work for me, I am trying to make it easy for her to track her time, so I created a clock in button, that creates a record in a database, I have it pop up a small window, that she can click to clockout when she is done working.
I want it to show her on that popup window a counter that will show how long she has been working, so I want to create a javascript or jQuery that will start at a certain time and count from there. She is on the East Coast, our company is in the Central Timezone, so 1 hour behind her.
How can I get a javascript to start from a certain time and keep updating the timer, so she can see something like this:
[You've been working for: 01:01:01 HH::MM::SS] - and it is actively updating, climbing up.
All the timers I've found are not about time itself, but about starting at a time and counting down, or starting at 0 and counting up.
Is there a way to tell it a start time, so that way if she reloads the page, it does not start from 0, but will start at the time she clocked in, then add the time since and start from there?
I know it can be done, but I'm more of a Perl guy than a Javascript guy. I'm doing this on Wordpress, so I could use PHP and just tell her to refresh the page to see the current amount of time and then have it on page load show the current amount of time, but I think having a counter would be better and make it easier for her.
is there some code already done that I could modify myself to make it work? I cannot find any, anywhere. I'm willing to do all the work, I'm not asking for someone to do it for me.
I found this example someone did:
function get_uptime() {
var t1 = new Date()
var t2 = new Date()
var dif = t1.getTime() - t2.getTime()
seconds = dif / 1000;
Seconds_Between_Dates = Math.abs(seconds);
document.getElementById("seconds").innerHTML = Seconds_Between_Dates;
setTimeout(get_uptime, 1000);
}
get_uptime();
That is sort of it, but I don't now how to put the first time in t1, what format do I put it in?
I can have PHP put it in any format, but not sure the one it needs.
Plus this appears to only put the seconds, not hours, minutes and seconds.
Is there away to do that?
Thanks,
Richard
From your question I understand you store the date and time on start?
So then you can use PHP to echo this information in a starting Date object and let a setInterval-function do the current timegetting and calculation of the time working.
See working example here: http://jsfiddle.net/c0rxkhyz/1/
This is the code:
var startDateTime = new Date(2014,0,1,23,59,59,0); // YYYY (M-1) D H m s ms (start time and date from DB)
var startStamp = startDateTime.getTime();
var newDate = new Date();
var newStamp = newDate.getTime();
var timer; // for storing the interval (to stop or pause later if needed)
function updateClock() {
newDate = new Date();
newStamp = newDate.getTime();
var diff = Math.round((newStamp-startStamp)/1000);
var d = Math.floor(diff/(24*60*60)); /* though I hope she won't be working for consecutive days :) */
diff = diff-(d*24*60*60);
var h = Math.floor(diff/(60*60));
diff = diff-(h*60*60);
var m = Math.floor(diff/(60));
diff = diff-(m*60);
var s = diff;
document.getElementById("time-elapsed").innerHTML = d+" day(s), "+h+" hour(s), "+m+" minute(s), "+s+" second(s) working";
}
timer = setInterval(updateClock, 1000);
<div id="time-elapsed"></div>
Attention! The month number in the new Date() declaration is minus one (so January is 0, Feb 1, etc)!
I would use momentJS fromNow function.
You can get the time started as variable on page load then call fromNow on that and current time to get time between the two every time the clock is clicked:
var StartedWorkDateTime = GetStartedTime();
moment(StartedWorkDateTime).fromNow(true);
Non momentJS:
var date1 = new Date("7/11/2010 15:00");
var date2 = new Date("7/11/2010 18:00");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffHours = Math.ceil(timeDiff / (1000 * 3600));
alert(diffHours);
reference
Get the difference between two dates by subtracting them:
var duration = end - start;
This will give you the number of milliseconds between the dates. You can use the milliseconds to figure out hours, minutes, and seconds. Then it's just a matter of string manipulation and writing the value to the page. To update the timer once per second, use setInterval():
setInterval(writeDuration, 1000);

Javascript setTimeout on iOS Safari

I am working on a little script that warns the user that his session is about to time out and his/her changes might not get saved.
On any browser, that works pretty well and I implemented a solution that just uses setTimeout to trigger a dialog box after a certain amount of time (unless the user takes certain actions in between).
On iOS Safari, however, this approach doesn't work, as the setTimeout gets "halted" while the user navigates to another app on his/her phone. Once the user opens Safari again and comes back to the page, the timer continues where it left off, rather than looking at the total time that expired.
Any suggestions on how to approach a session timeout warning that doesn't break on the iPhone?
Set the end time of the session in a variable.
Instead of using a counter, use javascript's date:
// get a date object
var today = new Date();
// ask the object for some information
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
var theHour = today.getHours();
Compare the end time to the current time every second
Disclaimer: Handle case where user returns and session has ended.

Categories

Resources