How to count up time in javascript (maybe with jquery) - javascript

On my app, I have a command:
#uptime = 'uprecords -s | awk '{ print $5 }'
that returns the current uptime from computer (using uptimed).
it returns something like 01:00:00 (hours, minutes, seconds) and I want to count up this time.
How do I do that? I tried some count up jquery plugins but none of them worked like I want
How do you guys count up?
Thanks in advance
edit
I think I wasn't clear enough
What I want is to catch this uptime from my server (already done it), and via javascript, make it dinamically, counting up this current uptime, so if the user got away from keyboard, by example, the uptime still increases

You can use setInterval:
var seconds = 2642; // uptime in seconds
var timer = setInterval(
function() {
seconds++;
}, 1000
);
Also, see this reference on JS time functions.

I've done something (ugly) like this:
function atualizarTimer() {
//span.uptimed is a string like 01:23:45
var time = $('span.uptimed').text();
var d = new Date();
times = time.split(':');
d.setHours(times[0]);
d.setMinutes(times[1]);
d.setSeconds(times[2]);
d.setSeconds(d.getSeconds()+1);
document.getElementById("uptimed").innerHTML = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
}

Related

Is there a way to watch times with moment.js and run a function when it does?

I'm new to moment.js and javascript and I couldn't seem to find anything in moment.js documentation or other questions here. I am comparing two different times, and would like to watch the time and run a function when Time A is equals to Time B.
so something like:
var a = TimeA
var b = TimeB
//watch the current time
when a === b {
//run a function
}
else {
//do nothing
}
There are many ways you can do this. But the most traditional way is to use an Interval Function as Badgy has pointed. Here is an working example for a 1 second interval:
var timeA = moment().add(10, 'seconds'); // 10 seconds from now
var tmr = setInterval(()=>{
var now = moment().unix();
var then = timeA.unix();
console.log(now, then)
if (now >= then) {
clearInterval(tmr);
console.log('Whatever you want to do');
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
I used .unix() method in moment.js because it returns the time in seconds. So it's better for comparison with the first time than a string like '2013-02-04T22:44:30.652Z' or the isSame() method because it uses milliseconds and can skip the exact moment. A second is a large enough time unit so it can be compared to the current time.
You could make a interval function and check every second if the times equal each other. Also throw a look at this it may help too.

How to get correct timestamp value in nodejs?

In my project my scheduling to post in social network sites using cron job,
timestamp value should end with zero instead of 1.
here is the node js code used:
var rule = new cron.RecurrenceRule();
rule.second = 0;
cron.scheduleJob(rule, function(){
var now = new Date();
var date = dateFormat(now, "dd-mm-yyyy, h:MM:ss TT");
console.log(Math.floor(new Date()/ 1000));
retrivepost(Math.floor(new Date()/ 1000).toString());
});
here is the timestamp value output log which i get in terminal
1517894101
1517894161
1517894221
1517894281
1517894341
1517894401
1517894461
1517894521
1517894581
1517894641
1517894701
1517894761
1517894821
1517894881
1517894941
1517895001
1517895061
1517895121
For me your code works just fine and logs timestamps ending with the zero second just like scheduled.
However, I think if your retrievepost() function depends on a timestamp being on the minute exactly you should round your date inside the .scheduleJob function to the nearest minute. A whole second later seems odd to me but imagine that you have some code just above that takes a while to compute. retrievepost() will fail then, even if you get it working right now.

Compare Server Time and Browser Time

My table that has 3 columns: FileName, LastUpdateTime, and a Restart button.
I need to display the restart button only if the last update time is more than 20 min ago. I get the last update time from the server. d = new Date() gives the local browser time but the lastUpdateTime is coming from the server. Server is in the different time zone than the clients browser.
The following code works if both server and browser are in the same time zone. Do you have any suggestions on how solve this if the server and browser are in a different time zone?
This application supposed to run anywhere in US and Europe.
var lastUpdatedTime = (gridData[i].LastTimeUpdated);
var d = new Date();
//deducting 20 min from current time
var deductTwenty = d.setMinutes(d.getMinutes() - 20);
var parsedupdatetime = Date.parse(lastUpdatedTime);
// If the last update time is not 20 ago, hide it.
if (parsedupdatetime > deductTwenty) {
newrestartButton.hide();
}
Use .NET in your .cshtml file to get the date server-side. Assuming you use MVC (since you tagged this question kendo-asp.net-mvc).
#{
var deductTwenty = DateTime.Now.AddMinutes(-20);
}
<script>
var jsDeductTwenty = new Date(#deductTwenty.Year, #deductTwenty.Month-1, #deductTwenty.Day, #deductTwenty.Hour, #deductTwenty.Minute);
</script>
Result:
What's probably going wrong is the server date parsing. Take a look at the Date.parse function spec - and make sure your server is returning something that will get parsed correctly like an ISO8601 formatted date.
You have to convert your lastUpdatedTime with client timezone, means you should convert server time to client time when subtracting date with 20 mins. You can use momentjs, moment-timezone and jstimezonedetect to achieve this.
Your code should be like this
// get current client timezone with jstimezonedetect
var currentTz = jstz.determine().name(); // e.g "Europe/London"
// parse last update time to moment object and change its timezone
var lastUpdateTime = moment(lastUpdatedTime, "M/DD/YYYY hh:mm a").tz(currentTz);
// create date using moment and deduct 20 mins from it
var deductTwenty = moment().subtract(20, 'minutes');
// now compare
if (lastUpdateTime > deductTwenty) {
newrestartButton.hide();
}
Hope this help.

Javascript: Storing the current time's timestamp value

Is there a way to store the current timestamp in a Javascript variable? The reason is I want to compare Javascript's current time value with a Django time variable, and whenever the time matches, it will send a popup notification.
I guess reloading the page maybe every 3 seconds or so would work, but that seems extremely inefficient.
I'm not sure exactly what you're trying to do here. It's not likely the times will ever match exactly unless you check every millisecond, but you can always check when the time is greater than the django variable, or within a certain range. This will check the time every three seconds.
var django = // Create a javascript date object from django timestamp here
var interval = setInterval(function(){checkTime()}, 3000);
function checkTime() {
var d = new Date();
if (d >= django) {
//Do something here
clearInterval(interval);
}
}

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