synchronising the Time without reloading the page - javascript

I'm building a web app that uses the Time of the computer I found how I can get the hours and the minutes and I succeeded to update them to the UI but the minute field is not synchronised with the time of the computer I have to reload the page to see it updated with the new value, I don't know how to solve this problem I feel like it's a stupid question but really I'm struggling with it, it's my first app with JavaScript so forgive me :p
I tried the setInterval but it didn't work too any help please
here is my code:
HTML
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>
Js
var hours=d.getHours();
var minutes=d.getMinutes();
var Time=" 03:19";
var newTime=Time.replace("03",hours);
var newTime=newTime.replace("19",minutes);
setInterval(function(){
document.querySelector(".Time").innerHTML=newTime;
},1000);
any better title for the question?
I feel it's not accurate

You need to get the date each time in callback passed to setInterval. I have added seconds also for test purpose.
You donot need to get the test of span and use replace() and then show. You could directly use Template Strings
`${hours}:${minutes}`
Tip for you is declare the element .Time in global scope and don't call querySelector every second
const span = document.querySelector(".Time");
setInterval(function(){
let date = new Date();
let hours = date.getHours();
let mins = date.getMinutes();
let seconds = date.getSeconds();
span.innerHTML= `${hours}:${mins}:${seconds}`;
},1000);
<div class="headTime" >Time: <span class="Time"> 03:19</span></div>
Note:If you are only showing the minutes no seconds you shouldn't call the function every second

Related

How to add input from a prompt to the local time using only JavaScript?

I'm a software engineering student in an Intro to JavaScript course and I'm stuck on an assignment. Here's the assignment,
in a file named alarmTime.html, use prompt() to find out how long the user wishes to nap. Then, write a statement to the document telling the user what time her/his alarm should go off. Be sure the times are local for the user.
I'm stuck on adding the input to the user's local time. I don't really know what I'm doing wrong and I'm having difficulty understanding what to do because all I'm getting is what seems to be random numbers. Please take a look at my code and point me in the right direction.
var howLong = prompt("How long, in hours, do you want to nap for?", 1);
var parsedInput = parseFloat(howLong);
var today = new Date();
var currentTime = today.toLocaleTimeString();
var myHour = today.getHours(currentTime);
var alarm = today.setHours(myHour + parsedInput);
document.write(alarm);
The reason is because of this statement document.write(alarm);. setHours method in Date object updates the Date instance, and returns the Date in milliseconds. Therefore, you are printing the Date object as the number of milliseconds since January 1, 1970. To fix that, simply replace it with document.write(today);
The problem is var alarm = today.setHours(myHour + parsedInput);
instead try to set the variable as
var alarm = today.getHours();
or change document.write(alarm); to document.write(today);
Date.now() will give you current time (users local time). Add time from prompt and your good:
let napTime = prompt('how many minutes do you want to nap?');
let alarmTime = new Date(Date.now()+napTime*60000);
//if you want to get HOURS instead of minutes
//let alarmTime = new Date(Date.now()+napTime*3600000);
//print it out. toLocale...() functions return local FORMAT of the datetime,
//they dont deal with timezones
document.write('set alarm to '+alarmTime.toLocaleTimeString('en-US'));
console.log(alarmTime);

update fullCalendar( ‘getDate’ ) regularly

I need to update a moment variable like
var moment = calendar.fullCalendar('getDate');
regularly by using setInterval function but that doesn't have any effect and the moment variable is always the same. Is there a method to have the current moment updated each X seconds ?
thanks,
Perhaps I've misunderstood, but it's not really clear why you want to use fullCalendar's getDate function. This will return the date currently selected in fullCalendar. Updating that every few seconds wouldn't be much use - it'll only change whenever the user selects a new date.
If you want to report the actual current time, you can do it easily using momentJS directly, something like this:
var m;
function currentTime() {
m = moment();
console.log(m.toISOString());
}
setInterval(currentTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

How do I update time on multiple rows using javascript

I'm using the fromNow function from moment.js library to display time elapsed from a specific date/time (e.g. '16 hours ago'). I use this within a table on multiple rows within my web app.
This part works fine, but I need the time to count continuously and for several rows (50 - 60 and growing). How do I get the time to count continuously and efficiently? I say efficiently because, I've read that using interval may be a bad idea so I'm not sure and I need help understanding.
This is how I create a cell which holds the elapsed time:
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(moment(data.checkintime).fromNow());
newCell.appendChild(newText);
Assuming the code you posted is correct, you can save the updated time in a variable and update all the rows. In that way, it's the same time that will display for all the rows and that time would just have to be done in one time:
var updatedTime = moment(data.checkintime).fromNow();
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(updatedTime);
newCell.appendChild(newText);
If you want the timestamp to continuously update, look into a library such as TimeAgo.
With your current code, simply change the text node to match timaeago's syntax <abbr title='{timestamp}' class='timeago'> and add the following javascript to the bottom of your page
jQuery(document).ready(function() {
jQuery("abbr.timeago").timeago();
});
This will continuously update the timestamp ("a moment ago", "2 minutes ago"....) which I believe is what you're looking for

How to compare datetime in javascript

I have been trying to get the code to work for more then 2 hours, then I tried this site, well there is alot of code here! I have used each of them. Some are in jQuery while some were pure JavaScript.
Here is two of the code that I have tried:
First code: This code was caught from this link: https://stackoverflow.com/a/2725097/1762944
var dateTimeStr = "17:10:03";
var user_time = DateTime.Parse( dateTimeStr );
var time_now = DateTime.Now;
if( time_now > user_time )
{
// your code...
}
Second code: This one is jQuery. It worked for the asker, and was marked as answer too. It works I have checked the fiddle provided by him! But when I tried the code, it didn't work either. Here:
function time_until() {
currentTime = Math.floor(jQuery.now() / 1000);
seconds = eventTime - currentTime;
if(second == 0){
//Stop voting
}
days = Math.floor(seconds / (60 * 60 * 24));
$('#time').html('seconds ' + seconds + '<br/>days ' + days);
}
I have tried to edit them both. But they don't work.
Reason why they work: The reason behind this all, is that what I want to do is,
I have a database table which is storing the time for users. I mean when they made an activity such like posting status updates!
I have created a timestamp. Which shows perfectly like this: few seconds ago.
Now what I want is, to update the time to 1 minute ago without reloading the page, like Facebook does. Or whatever the time is, to get updated to the next minute or hour or corresponding.
What I have tried is almost next to everything. But I guess the only issue with my codes is that when I place the DateTime.Now value from Database in it, it shows an error. The error is hidden so I have created an else statement like this:
if(seconds < 60) {
$("#jstime").html(seconds + "seconds..");
// else if minutes, if hours they are all written..and then an else
} else {
$("#jstime").html("Again an error, try again bud");
}
I have a setInterval which keeps on updating the id with the error text.
Here is the code that I am using.
<span id="timeval" title="#timeStamp">#TimeStamp</span></div>
<input type="hidden" id="time" value="9/23/2013 8:10:40 PM" />
<span>Real time: #TimeStamp</span><br>
<span id="update">Updated time: no update till now;</span><br>
<span id="jstime">Time</span>
The timeval is the real time that is being shown to the users, input is the time from where I get the value of the time on each post, the next span just shows the time to me, I mean I used this to check what was the time when the page was loaded, update is the span to show the updated time, jstime can also be used to show the updated time.
The problem is that you stored currentTime in the function you call every n seconds. As it gets looped it will everytime create a new current time.
Make it a global variable so you can loop through the function without creating the time new and use the old time instead.
Please go to link on stackoverflow and see my answer on how can we compare two dates along with the time in Javascript.

working with filenames and scheduled function calls in javascript

I have a couple questions about javascript:
Does javascript have the capability to identify a filename with a timestamp as a name?
Similar to the Perl code below utilizing the POSIX module?
my $filepath = sprintf("/path/to/file%s.JSON",strftime("%y%m%d",localtime));
this is just an example. I would like to find file in format yy/mm/dd/hh/min
For example say I want to find a file with the name 12_11_03_15:15.json how can I do this with javascript.
Say I create a function that I want to trigger every 15 minutes to read the file how is this possible with javascript? I looked at setInterval() but that won't work because it is dependent on when the browser is launched. Is it possible to schedule a function to execute every hh:00, hh:15, hh:30, hh:45?
Thank you very much in advance.
You can use the Date class to get information about the current time.
To schedule a function to run at a certain time, setInterval() is indeed the best choice. It seems like what you're really looking for is a way to find out when to start the first interval such that it will fall on a quarter-hour. For that, you should again use Date to get the current time and subtract it from the next quarter-hour; you can use the resulting value with setTimeout to time the start of the first interval.
Here's an example: http://jsfiddle.net/GSF6C/3/
var nextQuarterHour = new Date();
nextQuarterHour.setMilliseconds(0);
nextQuarterHour.setSeconds(0);
do {
nextQuarterHour.setMinutes(nextQuarterHour.getMinutes() + 1);
} while (nextQuarterHour.getMinutes() % 15)
var millisecondsToNextQuarterHour = nextQuarterHour.getTime() - Date.now();
document.write(millisecondsToNextQuarterHour);
setTimeout(function () {
alert("Ding!");
setInterval(function () { alert("Dong!"); }, 15 * 60 * 1000);
}, millisecondsToNextQuarterHour);
​
​

Categories

Resources